异步任务两两嵌套依赖的信号量实现
目标
(A) (B) (C)
| | |
| | |
| | |
+++++ +++++
| |
| |
| |
(D) (E)
ABC 三个异步任务两两组合,双双完成之后才触发 D E 两个任务。
使用信号量,完成任务。
实现
dispatch_semaphore_t semaphore1 = dispatch_semaphore_create(0);
dispatch_semaphore_t semaphore2 = dispatch_semaphore_create(0);
dispatch_semaphore_t semaphore3 = dispatch_semaphore_create(0);
dispatch_semaphore_t semaphore4 = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
sleep(2);
NSLog(@"mission A");
dispatch_semaphore_signal(semaphore1); //++1
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
sleep(3);
NSLog(@"mission B");
dispatch_semaphore_signal(semaphore2); //++1
dispatch_semaphore_signal(semaphore3); //++1
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
sleep(5);
NSLog(@"mission C");
dispatch_semaphore_signal(semaphore4); //++1
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
dispatch_semaphore_wait(semaphore1, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(semaphore2, DISPATCH_TIME_FOREVER);
NSLog(@"mission D");
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
dispatch_semaphore_wait(semaphore3, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(semaphore4, DISPATCH_TIME_FOREVER);
NSLog(@"mission E");
});
在任务 D 里 wait A B 的信号量,在任务 E 里 wait B C 的信号量,B 发送两个信号量