iOS信号量主要用于GCD对线程安全的控制
其中有三个主要的函数
dispatch_semaphore_t semaphore = dispatch_semaphore_create(number); // 创建一个值为number的信号量
dispatch_semaphore_wait(semaphore,等待时间); //如果该信号量的值大于0,则使其信号量的值-1,否则,阻塞线程直到该信号量的值大于0或者达到等待时间。
dispatch_semaphore_signal(semaphore); //释放信号量,使得该信号量的值加1
使用场景
主要是控制线程并发数
比如
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
sleep(1);
NSLog(@"1");
dispatch_semaphore_signal(semaphore);
});
dispatch_async(queue, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
sleep(1);
NSLog(@"2");
dispatch_semaphore_signal(semaphore);
});
dispatch_async(queue, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
sleep(1);
NSLog(@"3");
dispatch_semaphore_signal(semaphore);
});
dispatch_async(queue, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
sleep(1);
NSLog(@"4");
dispatch_semaphore_signal(semaphore);
});
上面的代码只会一个一个执行
如果我们把信号值设置为2,那就可以两个一起执行
阻塞请求
有时候我们需要等待多个线程执行完毕,来处理一些其他的事情,而且这些线程并不需要执行顺序,,一般我们是使用dispatch_group来进行操作,但是我们也可以使用GCD信号量来操作
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_sync(queue, ^{
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_async(queue, ^{
// dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
sleep(1);
NSLog(@"1");
dispatch_semaphore_signal(semaphore);
});
dispatch_async(queue, ^{
// dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
sleep(1);
NSLog(@"2");
dispatch_semaphore_signal(semaphore);
});
dispatch_async(queue, ^{
// dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
sleep(1);
NSLog(@"3");
dispatch_semaphore_signal(semaphore);
});
dispatch_async(queue, ^{
// dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
sleep(1);
NSLog(@"4");
dispatch_semaphore_signal(semaphore);
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"5");
});
以上代码打印 5的值始终在最后,这样我们就可以在所有线程执行完毕后去处理一些其他逻辑了
网友评论