IOS-GCD多线程

同步 & 异步:

区别在于会不会阻塞线程:同步会等待当前任务结束再去执行下一个任务;异步是同时进行执行任务。

串行 & 并行:

 dispatch_get_main_queue   -->主线程的队列
 dispatch_get_global_queue -->全局线程的队列(全局并发的)

简单的例子:

dispatch_async(dispatch_get_global_queue(0,0), ^{
    NSLog(@"Task Thread!");
    [NSThread sleepTimeInterval:3];
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@" UI Thread!")
    });
});

自定义线程:

串行:
创建一个自定义的线程,该线程是一个同步线程。如下执行的了两个dispatch_async,实际上是同一个线程,task1和task2会按照先后顺序执行。
默认NULL 就是 DISPATCH_QUEUE_SEARIAL

dispatch_queue_t queue = dispatch_queue_create(@"gcd_queue", NULL);
dispatch_async(queue, ^{
    NSLog(@"task 1");
    [NSthread sleepForTimeInterval:2];
    NSLog(@"task 1 over");
});

dispatch_async(queue, ^{
    NSLog(@"task 2");
    [NSthread sleepForTimeInterval:2];
    NSLog(@"task 2 over");
});

并行:
DISPATCH_QUEUE_CONCURRENT 参数创建一个并行的队列。

dispatch_queue_t queue = dispatch_queue_create(@"gcd_queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
    NSLog(@"task 1");
    [NSthread sleepForTimeInterval:2];
    NSLog(@"task 1 over");
});

dispatch_async(queue, ^{
    NSLog(@"task 2");
    [NSthread sleepForTimeInterval:2];
    NSLog(@"task 2 over");
});

GCD_group的使用:

dispatch_queue_t queue = dispatch_queue_create(@"gcd_queue", DISPATCH_QUEUE_CONCURRENT);
//创建一个group
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
    NSLog(@"task 1");
    [NSthread sleepForTimeInterval:2];
    NSLog(@"task 1 over");
});

dispatch_group_async(group, queue, ^{
    NSLog(@"task 2");
    [NSthread sleepForTimeInterval:2];
    NSLog(@"task 2 over");
});

dispatch_group_notify(group, queue, ^{
    NSLog(@"All task over!");
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@" UI Thread!")
    });
});

异步线程控制方法:

dispatch_queue_t queue = dispatch_queue_create(@"gcd_queue", DISPATCH_QUEUE_CONCURRENT);
//创建一个group
dispatch_group_t group = dispatch_group_create();
//载入group
dispatch_group_enter(group);
    .
    .     //执行内容
    .
//用完释放group
dispatch_group_leave(group);

你可能感兴趣的:(IOS)