GCD组(dispatch_group_t)和GCD信号量(di
2019-05-30 本文已影响0人
coming_168
- GCD组主要涉及到以下四个函数配合使用:
dispatch_group_t group = dispatch_group_create(); //创建group
dispatch_group_enter(group); //进入group
dispatch_group_leave(group); //离开group
// 等待通知
dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
// 执行code
});
测试代码如下:
- (void)asyncGroup{
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
dispatch_group_enter(group);
//模拟多线程耗时操作
dispatch_group_async(group, globalQueue, ^{
sleep(3);
NSLog(@"%@---block1结束",[NSThread currentThread]);
dispatch_group_leave(group);
});
NSLog(@"%@结束1",[NSThread currentThread]);
dispatch_group_enter(group);
//模拟多线程耗时操作
dispatch_group_async(group, globalQueue, ^{
sleep(3);
NSLog(@"%@---block2结束",[NSThread currentThread]);
dispatch_group_leave(group);
});
NSLog(@"%@结束2",[NSThread currentThread]);
dispatch_group_notify(group, globalQueue, ^{
NSLog(@"%@---全部结束",[NSThread currentThread]);
});
}
打印结果:
image.png- GCD信号量机制主要涉及到以下三个函数:
dispatch_semaphore_create(long value); // 创建信号量
dispatch_semaphore_signal(dispatch_semaphore_t deem); // 发送信号量
dispatch_semaphore_wait(dispatch_semaphore_t dsema, dispatch_time_t timeout); // 等待信号量
测试代码如下:
- (void)semaphoreTest {
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"任务1---->%@",[NSThread currentThread]);
dispatch_semaphore_signal(sem);
});
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
NSLog(@"任务1完成---->%@",[NSThread currentThread]);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"任务2---->%@",[NSThread currentThread]);
dispatch_semaphore_signal(sem);
});
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
NSLog(@"任务2完成---->%@",[NSThread currentThread]);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"任务3---->%@",[NSThread currentThread]);
dispatch_semaphore_signal(sem);
});
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
NSLog(@"任务3完成---->%@",[NSThread currentThread]);
}