GCD信号量机制
Posted zhengweifang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了GCD信号量机制相关的知识,希望对你有一定的参考价值。
1.创建信号量,创建的初始值决定线程并发数
dispatch_semaphore_t semaphore = dispatch_semaphore_create(2);
2.等待信号
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
// 由于是异步执行的,所以每次循环Block里面的dispatch_semaphore_signal根本还没有执行就会执行dispatch_semaphore_wait,从而semaphore-1.当循环10此后,semaphore等于0,则会阻塞线程,直到执行了Block的dispatch_semaphore_signal 才会继续执行
3.发信号,信号量值会加1
dispatch_semaphore_signal(semaphore);
4.信号量可使多个异步线程同步执行
dispatch_semaphore_t semaphore1 = dispatch_semaphore_create(0);
dispatch_semaphore_t semaphore2 = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
NSLog(@"thread 2");
sleep(2);
dispatch_semaphore_signal(semaphore2);
);
dispatch_semaphore_wait(semaphore2, DISPATCH_TIME_FOREVER);
NSLog(@"thread 1");
sleep(2);
dispatch_semaphore_signal(semaphore1);
);
dispatch_semaphore_wait(semaphore1, DISPATCH_TIME_FOREVER);
NSLog(@"main thread");
以上是关于GCD信号量机制的主要内容,如果未能解决你的问题,请参考以下文章
swift Grand Central Dispatch(GCD)发送信号量示例
iOS底层探索之多线程—GCD源码分析( 信号量dispatch_semaphore_t)