在GCD中有三个函数是semaphore的操作,分别是:
创建一个semaphore
- dispatch_semaphore_create(int)
发送一个信号
- dispatch_semaphore_signal(dispatch_semaphore)
等待信号
- dispatch_semaphore_wait(dispatch_semaphore, int)
注:
(1)wait 将信号量 -1
(2)signal 将信号量 +1
(3)wait 直到信号量 >=0 继续执行
代码1:
__block dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_queue_t queue = dispatch_queue_create("StudyBlocks", NULL);
dispatch_async(queue, ^(void) {
for (int i = 0; i < 5; i ++) {
NSLog(@">> i: %d", i);
}
dispatch_semaphore_signal(semaphore);
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
for (int j = 0; j < 5; j ++) {
NSLog(@">> Main Data: %d", j);
}
结果1:
2016-04-20 15:36:40.406 GCD semaphorea[3808:1129079] >> i: 0
2016-04-20 15:36:40.407 GCD semaphorea[3808:1129079] >> i: 1
2016-04-20 15:36:40.407 GCD semaphorea[3808:1129079] >> i: 2
2016-04-20 15:36:40.407 GCD semaphorea[3808:1129079] >> i: 3
2016-04-20 15:36:40.407 GCD semaphorea[3808:1129079] >> i: 4
2016-04-20 15:36:40.407 GCD semaphorea[3808:1129048] >> j: 0
2016-04-20 15:36:40.407 GCD semaphorea[3808:1129048] >> j: 1
2016-04-20 15:36:40.407 GCD semaphorea[3808:1129048] >> j: 2
2016-04-20 15:36:40.407 GCD semaphorea[3808:1129048] >> j: 3
2016-04-20 15:36:40.408 GCD semaphorea[3808:1129048] >> j: 4
代码2:
__block dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
dispatch_queue_t queue = dispatch_queue_create("StudyBlocks", NULL);
dispatch_async(queue, ^(void) {
for (int i = 0; i < 5; i ++) {
NSLog(@">> i: %d", i);
}
dispatch_semaphore_signal(semaphore);
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
for (int j = 0; j < 5; j ++) {
NSLog(@">> j: %d", j);
}
结果2:
2016-04-20 15:37:35.335 GCD semaphorea[3814:1129617] >> i: 0
2016-04-20 15:37:35.335 GCD semaphorea[3814:1129589] >> j: 0
2016-04-20 15:37:35.336 GCD semaphorea[3814:1129589] >> j: 1
2016-04-20 15:37:35.336 GCD semaphorea[3814:1129589] >> j: 2
2016-04-20 15:37:35.336 GCD semaphorea[3814:1129589] >> j: 3
2016-04-20 15:37:35.336 GCD semaphorea[3814:1129589] >> j: 4
2016-04-20 15:37:35.337 GCD semaphorea[3814:1129617] >> i: 1
2016-04-20 15:37:35.337 GCD semaphorea[3814:1129617] >> i: 2
2016-04-20 15:37:35.337 GCD semaphorea[3814:1129617] >> i: 3
2016-04-20 15:37:35.337 GCD semaphorea[3814:1129617] >> i: 4