1、dispatch_semaphore_create:創(chuàng)建一個Semaphore并初始化信號的總量
2、dispatch_semaphore_signal:發(fā)送一個信號,讓信號總量加1
3、dispatch_semaphore_wait:可以使總信號量減1,當信號量為0時就是一直等待(阻塞當前線程),否則就可以正常執(zhí)行。
注意:信號量的使用前提是:想清楚需要處理哪個線程等待(阻塞),又要哪個線程繼續(xù)執(zhí)行,然后使用信號量。
一、GCD 信號量實現(xiàn)線程同步,將異步操作轉(zhuǎn)換成同步操作
信號量
初始化信號量
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
NSLog(@"2-------");
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:5];
NSLog(@"異步結(jié)果------");
dispatch_semaphore_signal(semaphore);
});
//信號量+1
NSLog(@"3-------");
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"4-------");
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"5-------");

截屏2022-09-07 下午4.10.11.png
二、線程安全 -- 多數(shù)據(jù)保護同一數(shù)據(jù)安全操作
dispatch_semaphore_t semaphoreLock = dispatch_semaphore_create(1);
self.ticketSurplusCount = 50;
//隊列任務(wù)
dispatch_queue_t queue1 = dispatch_queue_create("net.bujige.testQueue1",
DISPATCH_QUEUE_SERIAL);
// 隊列任務(wù)
dispatch_queue_t queue2 = dispatch_queue_create("net.bujige.testQueue2",
DISPATCH_QUEUE_SERIAL);
__weak typeof(self) weakSelf = self;
dispatch_async(queue1, ^{
[weakSelf saleTicketSafe];
});
dispatch_async(queue2, ^{
[weakSelf saleTicketSafe];
});
- (void)saleTicketSafe {
while (1) {
dispatch_semaphore_wait(semaphoreLock, DISPATCH_TIME_FOREVER);
if (self.ticketSurplusCount > 0) {
self.ticketSurplusCount--;
[NSThread sleepForTimeInterval:0.2];
} else {
}
dispatch_semaphore_signal(semaphoreLock);
break;
}
dispatch_semaphore_signal(semaphoreLock);
}
}