dispatch_semaphore_t
一种计算的信号量
dispatch_semaphore_create
创建一个数值的信号量
dispatch_semaphore_signal
对指定的信号量进行增加1
dispatch_semaphore_wait
会使传入的信号量减1,如果返回的值为0说明有任务进行中就阻碍当前的线程,如果返回的值大于0,就代表当前的线程当中没有任务再执行,就接着执行下面的任务。
用这个可以起到顺序执行异步任务的功效。
如果后一步的执行需要前一步执行完拿到结果才行的话,这也是一种异步顺序执行的方案。
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self task:@"task one starting"];
dispatch_semaphore_signal(semaphore);
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self task:@"task two starting"];
dispatch_semaphore_signal(semaphore);
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self task:@"task three starting"];
dispatch_semaphore_signal(semaphore);
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
// Do any additional setup after loading the view, typically from a nib.
}
- (void)task:(NSString *)taskName{
NSLog(@"%@",taskName);
sleep(1);
}
先执行dispatch_semaphore_wait 然后发现线程任务还在进行,就开始堵塞当前任务的线程,等待dispatch_async内部执行完成信号量+1才会继续下面的执行。