dispatch_semaphore_t GCD的锁机制,是自旋锁,持有计数的信号
dispatch_semaphore_create 创建信号量
dispatch_semaphore_wait 信号量-1,-1之后小于0时,线程阻塞,并以FIFO方式等待资源
dispatch_semaphore_signal 信号量+1,+1之后大于0时,并以FIFO的方式唤醒等待的线程
实现代码
- (void)group_display11 {
/// 创建一个调度组
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t theGlobalQueue = dispatch_get_global_queue(0, 0);
dispatch_queue_t theSerialQueue = dispatch_queue_create("com.junes.serial.queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_queue_t theConcurrentQueue = dispatch_queue_create("com.junes.serial.queue", DISPATCH_QUEUE_CONCURRENT);
/// 将任务丢进调度组
dispatch_group_async(group, theGlobalQueue, ^{
NSLog(@"任务1 开始 +++++++");
/// 模拟耗时操作
sleep(2);
NSLog(@"任务1 完成 -----------------");
});
dispatch_group_async(group, theSerialQueue, ^{
NSLog(@"任务2 开始 +++++++");
/// 模拟耗时操作
sleep(4);
NSLog(@"任务2 完成 -----------------");
});
dispatch_group_enter(group);
/// 模拟异步网络请求
dispatch_async(theConcurrentQueue, ^{
NSLog(@"任务3 开始 +++++++");
sleep(5);
NSLog(@"任务3 完成 -----------------");
dispatch_group_leave(group);
});
NSLog(@"dispatch_group_wait 即将囚禁线程");
/// 传入指定调度组,与超时时间(DISPATCH_TIME_FOREVER 代表永不超时,DISPATCH_TIME_NOW 代表立马超时,完全搞不懂这个有什么用)。
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
NSLog(@"dispatch_group_wait 释放了线程");
// 调度组内所有任务都完成了,该做什么就做什么
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"所有任务完成了");
});
}
- (void)semaphore_action{
__block int theNumber = 0;
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"task1 start ----%@",[NSThread currentThread]);
for (int i =0; i < 10000000; i++) {
theNumber++;
}
NSLog(@"task1 finished ----%@",[NSThread currentThread]);
dispatch_semaphore_signal(semaphore);
});
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"task2 start ----%@",[NSThread currentThread]);
for (int i =0; i < 10000; i++) {
theNumber--;
}
NSLog(@"task2 finished ----%@",[NSThread currentThread]);
dispatch_semaphore_signal(semaphore);
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"finished theNumber ====%i",theNumber);
});
}
2020-10-30 10:43:25.762002+0800 GCDPropertyQueue[3778:348773] task1 start ----<NSThread: 0x6000003c4bc0>{number = 6, name = (null)}
2020-10-30 10:43:25.779043+0800 GCDPropertyQueue[3778:348773] task1 finished ----<NSThread: 0x6000003c4bc0>{number = 6, name = (null)}
2020-10-30 10:43:25.779237+0800 GCDPropertyQueue[3778:348772] task2 start ----<NSThread: 0x6000003fdd00>{number = 4, name = (null)}
2020-10-30 10:43:25.779378+0800 GCDPropertyQueue[3778:348772] task2 finished ----<NSThread: 0x6000003fdd00>{number = 4, name = (null)}
2020-10-30 10:43:25.779502+0800 GCDPropertyQueue[3778:348531] finished theNumber ====9990000