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");