dispatch_semaphore_t semaphoer = dispatch_semaphore_create(2);
dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(quene, ^{
dispatch_semaphore_wait(semaphoer, DISPATCH_TIME_FOREVER);
NSLog(@"run task 1");
sleep(2);
NSLog(@"complete task 1");
dispatch_semaphore_signal(semaphoer);
});
NSLog(@"run task 1.");
dispatch_async(quene, ^{
dispatch_semaphore_wait(semaphoer, DISPATCH_TIME_FOREVER);
NSLog(@"run task 2");
sleep(1);
NSLog(@"complete task 2");
dispatch_semaphore_signal(semaphoer);
});
NSLog(@"run task 2.");
dispatch_async(quene, ^{
dispatch_semaphore_wait(semaphoer, DISPATCH_TIME_FOREVER);
NSLog(@"run task 3");
sleep(1);
NSLog(@"complete task 3");
dispatch_semaphore_signal(semaphoer);
});
NSLog(@"run task 3.");
打印结果如下
2018-08-13 16:20:51.351316+0800 BigCatProtect[35549:7281594] run task 1.
2018-08-13 16:20:51.351330+0800 BigCatProtect[35549:7281810] run task 1
2018-08-13 16:20:51.351467+0800 BigCatProtect[35549:7281594] run task 2.
2018-08-13 16:20:51.351528+0800 BigCatProtect[35549:7281811] run task 2
2018-08-13 16:20:51.351687+0800 BigCatProtect[35549:7281594] run task 3.
2018-08-13 16:20:52.354321+0800 BigCatProtect[35549:7281811] complete task 2
2018-08-13 16:20:52.355861+0800 BigCatProtect[35549:7281812] run task 3
2018-08-13 16:20:53.355663+0800 BigCatProtect[35549:7281810] complete task 1
2018-08-13 16:20:53.358234+0800 BigCatProtect[35549:7281812] complete task 3
设置信号量为2 就是当前可以执行 两个任务。第三个任务 只有当其他当执行完之后才可以执行。