1侦讨、dispatch_semaphore_create:創(chuàng)建一個(gè)Semaphore并初始化信號(hào)的總量
2骡和、dispatch_semaphore_signal:發(fā)送一個(gè)信號(hào)锥涕,讓信號(hào)總量加1
3扶认、dispatch_semaphore_wait:可以使總信號(hào)量減1,當(dāng)信號(hào)量為0時(shí)就是一直等待(阻塞當(dāng)前線程)粱挡,否則就可以正常執(zhí)行赠幕。
注意:信號(hào)量的使用前提是:想清楚需要處理哪個(gè)線程等待(阻塞),又要哪個(gè)線程繼續(xù)執(zhí)行询筏,然后使用信號(hào)量榕堰。
一、GCD 信號(hào)量實(shí)現(xiàn)線程同步嫌套,將異步操作轉(zhuǎn)換成同步操作
信號(hào)量
初始化信號(hào)量
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);
});
//信號(hào)量+1
NSLog(@"3-------");
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"4-------");
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"5-------");
二逆屡、線程安全 -- 多數(shù)據(jù)保護(hù)同一數(shù)據(jù)安全操作
dispatch_semaphore_t semaphoreLock = dispatch_semaphore_create(1);
self.ticketSurplusCount = 50;
//隊(duì)列任務(wù)
dispatch_queue_t queue1 = dispatch_queue_create("net.bujige.testQueue1",
DISPATCH_QUEUE_SERIAL);
// 隊(duì)列任務(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);
}
}