美文网首页
GCD组(dispatch_group_t)和GCD信号量(di

GCD组(dispatch_group_t)和GCD信号量(di

作者: coming_168 | 来源:发表于2019-05-30 09:14 被阅读0次
  • 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]);
}
打印结果如下(相当于是用GCD的信号量来实现异步线程同步操作):
image.png

相关文章

网友评论

      本文标题:GCD组(dispatch_group_t)和GCD信号量(di

      本文链接:https://www.haomeiwen.com/subject/puaptctx.html