@property (nonatomic, strong) dispatch_queue_t serialQueue;
@property (nonatomic, strong) dispatch_semaphore_t semaphore;
self.serialQueue = dispatch_queue_create("serial_queue", DISPATCH_QUEUE_SERIAL);
self.semaphore = dispatch_semaphore_create(3);
创建单任务队列和信号,信号量为3
__weak typeof(self) weakSelf = self;
__block NSUInteger count = 0;
for (int i = 0; i < 10; i++) {
dispatch_async(self.serialQueue, ^{
dispatch_semaphore_wait(weakSelf.semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"index %d", i);
});
}
执行上面的代码,会打印0 1 2
每执行一个任务就会消耗一个信号量,信号量为0时线程被阻塞
dispatch_semaphore_signal(self.semaphore);
当再增加一个信号量,会打印 3,以此类推
信号量通常用于一个任务中有大量任务需要完全处理完成才能执行下一任务时
或者其中有异步任务,需要等待异步返回结果
dispatch_semaphore_wait 和 dispatch_semaphore_signal一对一
一般情况或者需要阻塞未知数量的任务时,可以这样写
self.semaphore = dispatch_semaphore_create(0);
dispatch_async(self.serialQueue, ^{
dispatch_semaphore_wait(weakSelf.semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"index %d", i);
dispatch_semaphore_signal(weakSelf.semaphore);
);
阻塞多任务的机会只有一次