信号量Semaphore
信号量是多线程编程中一项很重要的技术。在GCD中,使用dispatch_semaphore来表示信号量,相关函数有3个:
1、dispatch_semaphore_create(value) 创建信号量,参数表示信号量的数值(可以简单的理解为同时能有几个线程执行操作)
2、dispatch_semaphore_wait(semaphore,time) 等待信息量,即把信号量数值减一。第一个参数为信号量对象,第二个为等待超时的时间
3、dispatch_semaphore_singal(semaphore) 发送一个信号,即信息量数值加一。参数为信号量对象
信号量技术,通常用来:
1、使异步操作变为同步操作
2、加锁操作,保证线程安全
话不多说,上代码。
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_block_t task1 = dispatch_block_create(0, ^{
NSLog(@" task1 begin");
[NSThread sleepForTimeInterval:5];
NSLog(@"task1 end");
});
dispatch_block_t task2 = dispatch_block_create(0, ^{
NSLog(@" task2 begin");
[NSThread sleepForTimeInterval:1.5];
NSLog(@"task2 end");
});
dispatch_block_t task3 = dispatch_block_create(0, ^{
NSLog(@" task3 begin");
[NSThread sleepForTimeInterval:3];
NSLog(@"task3 end");
});
dispatch_async(concurrentQueue, ^{
task1();
});
dispatch_async(concurrentQueue, ^{
dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
task2();
dispatch_semaphore_signal(semaphore);
});
dispatch_async(concurrentQueue, ^{
dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
task3();
dispatch_semaphore_signal(semaphore);
});
dispatch_block_notify(task1, dispatch_get_main_queue(), ^{
dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
NSLog(@"this is main thread,refreshUI");
dispatch_semaphore_signal(semaphore);
});
以上代码,使用信号量,结合dispatch_block_notify,实现了task3在task2执行结束后再执行,task4(刷新UI的操作)在所有任务执行结束后再执行。当然也可以使用dispatch_group实现相同的业务场景,其实dispatch_group底层就是用dispathch_semaphore来实现的。
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
dispatch_queue_t queue1 = dispatch_queue_create("queue1", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t queue2 = dispatch_queue_create("queue2", DISPATCH_QUEUE_SERIAL);
dispatch_block_t task = ^{
while(true) {
dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
if(self.theCount>0) {
self.theCount--;
NSLog(@"%@吃掉了一个苹果,剩余%d个苹果",[NSThread currentThread],self.theCount);
[NSThread sleepForTimeInterval:0.2];
}else{
NSLog(@"没有苹果了");
dispatch_semaphore_signal(semaphore);
break;//没有时跳出循环
}
dispatch_semaphore_signal(semaphore);
}
};
dispatch_async(queue1, task);
dispatch_async(queue2, task);
以上代码,使用信号量,实现了锁操作,保证线程安全。