dispatch_semaphore信号量实现线程同步

2020-07-06  本文已影响0人  Jean_Lina
  • Dispatch Semaphore提供了三个函数:
  1. dispatch_semaphore_create:创建一个Semaphore并初始化信号的总量
  2. dispatch_semaphore_signal:发送一个信号,让信号总量加1
  3. dispatch_semaphore_wait:可以使总信号量减1,当信号总量为0时就会一直等待(阻塞所在线程),否则就可以正常执行。
#pragma mark dispatch_semaphore信号量
- (void)gcd_dispatch_semaphore {
    //打印当前线程
    NSLog(@"currentThread---%@",[NSThread currentThread]);
    NSLog(@"semaphore---begin");
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    __block NSInteger number = 0;
    dispatch_async(queue, ^{
        // 追加任务1
        //模拟耗时操作
        [NSThread sleepForTimeInterval:2];
        //打印当前线程
        NSLog(@"1---%@",[NSThread currentThread]);
        number = 100;
        dispatch_semaphore_signal(semaphore);
    });
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    NSLog(@"semaphore---end,number = %ld",(long)number);
}

输出结果:
2020-07-06 15:28:49.979677+0800 GCD[2989:1190741] currentThread---<NSThread: 0x2804b4f80>{number = 1, name = main}
2020-07-06 15:28:49.979764+0800 GCD[2989:1190741] semaphore---begin
2020-07-06 15:28:51.984955+0800 GCD[2989:1190767] 1---<NSThread: 0x28048f400>{number = 3, name = (null)}
2020-07-06 15:28:51.985111+0800 GCD[2989:1190741] semaphore---end,number = 100
上一篇 下一篇

猜你喜欢

热点阅读