GCD同步

dispatch_group_t

一组任务完成后再做其他处理,比如异步下载多张图片,等图片下载完成后再拼接图片显示,这种类似需求就可以用group来完成

1.一组同步任务:

- (void)testGroup1
{
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_queue_create("com.test.queue1", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_async(group, queue, ^{
        sleep(3);
        NSLog(@"sync 1 sleep 3s");
    });
    
    dispatch_group_async(group, queue, ^{
        sleep(1);
        NSLog(@"sync 2 sleep 1s");
    });
    
    //notify中的queue可以是任意一个queue,是希望处理block中任务的queue
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"all sync done");
    });
}

2.一组异步任务

- (void)testGroup2
{
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_queue_create("com.test.queue2", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_enter(group);
    dispatch_async(queue, ^{
        sleep(3);
        NSLog(@"async 1 sleep 3s");
        dispatch_group_leave(group);
    });
    
    dispatch_group_enter(group);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        sleep(1);
        NSLog(@"async 2 sleep 1s");
        dispatch_group_leave(group);
    });
    
    //阻塞当前线程,直到指定超时时间(DISPATCH_TIME_FOREVER 永久阻塞)
    dispatch_group_wait(group, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5*NSEC_PER_SEC)));
//    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
    
    NSLog(@"all async done");
}

- (void)testGroup3
{
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_queue_create("com.test.queue1", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_enter(group);
    dispatch_async(queue, ^{
        sleep(3);
        NSLog(@"sync 1 sleep 3s");
        dispatch_group_leave(group);
    });
        
    dispatch_group_enter(group);
    dispatch_async(queue, ^{
        sleep(1);
        NSLog(@"sync 2 sleep 1s");
        dispatch_group_leave(group);
     });
        
     dispatch_group_notify(group, dispatch_get_main_queue(), ^{
         NSLog(@"all sync done");
     });
}

dispatch_barrier_async

在它前面加入的同一队列的任务执行结束后它才执行,而且它后面加入的同一队列的任务等它执行完成之后才会执行

dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
dispatch_async(globalQueue, ^{
    [NSThread sleepForTimeInterval:3];
    NSLog(@"dispatch_async1");
});

dispatch_async(globalQueue, ^{
    [NSThread sleepForTimeInterval:1];
    NSLog(@"dispatch_async2");
});

dispatch_barrier_async(globalQueue, ^{
    [NSThread sleepForTimeInterval:2];
    NSLog(@"dispatch_barrier_async");
});

dispatch_async(globalQueue, ^{
    [NSThread sleepForTimeInterval:1];
    NSLog(@"dispatch_async3");
});

dispatch_apply

循环执行某个任务指定次数

dispatch_apply(6, dispatch_get_global_queue(0, 0), ^(size_t index) {
    NSLog(@"执行:%zu", index);
});

你可能感兴趣的:(GCD同步)