GCD 信号量

1、dispatch_semaphore_create:创建一个Semaphore并初始化信号的总量
2、dispatch_semaphore_signal:发送一个信号,让信号总量加1
3、dispatch_semaphore_wait:可以使总信号量减1,当信号量为0时就是一直等待(阻塞当前线程),否则就可以正常执行。

注意:信号量的使用前提是:想清楚需要处理哪个线程等待(阻塞),又要哪个线程继续执行,然后使用信号量。

一、GCD 信号量实现线程同步,将异步操作转换成同步操作

信号量

初始化信号量

  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(@"异步结果------");
        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

二、线程安全 -- 多数据保护同一数据安全操作

dispatch_semaphore_t  semaphoreLock = dispatch_semaphore_create(1);

self.ticketSurplusCount = 50;

 //队列任务 
 dispatch_queue_t queue1 = dispatch_queue_create("net.bujige.testQueue1", 
DISPATCH_QUEUE_SERIAL);
 // 队列任务
 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);
 }
}

你可能感兴趣的:(GCD 信号量)