定义在semaphore.h中,一共三个api
- 创建信号量
dispatch_semaphore_t
dispatch_semaphore_create(intptr_t value);
- 信号量-1
intptr_t
dispatch_semaphore_wait(dispatch_semaphore_t dsema, dispatch_time_t timeout);
- 信号量+1
intptr_t
dispatch_semaphore_signal(dispatch_semaphore_t dsema);
原理:调用dispatch_semaphore_wait之后信号量-1,信号量大于等于0继续执行,否则锁住临界区;调用dispatch_semaphore_signal之后信号量+1,信号量大于等于0继续执行
使用
dispatch_semaphore_t semaphore = dispatch_semaphore_create(5);
NSInteger n = 10;
while (n--) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"%ld:%@", (long)n, [NSThread currentThread]);
sleep(1);
dispatch_semaphore_signal(semaphore);
});
}
场景:
控制最大并发数,当并发数为1的时候就是串行,即可以当做互斥锁使用