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

2019-05-30  本文已影响0人  coming_168
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
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
上一篇下一篇

猜你喜欢

热点阅读