iOS-多线程之GCD

iOS实现多线程编程有四种方式Pthreads,NSThread,NSOperation & NSOperationQueue和GCD.GCD(Grand Central Dispatch)是异步执行任务的技术之一,一般将应用程序中线程管理代码在系统级实现.开发过程中只需要定义想执行的任务并追加到适当的Dispatch Queue,GCD就能生成必要的线程执行任务.

GCD以其难以置信的API风格,实现了极其复杂繁琐的多线程编程,是多线程编程中必不可少一把利剑.GCD属于系统级的线程管理,GCD中的FIFO队列称为dispatch queue,用来保证先进来的任务先得到执行.

基础概念

进程是一个正在执行程序的实例,在iOS中可以理解为一个正在运行App,每个进程都有一个单独的Process ID(进程ID).现在操作系统将线程作为基本的操作单元,线程是一组寄存器的状态,一个进程包含了多个线程.一个进程内的所有线程都共享虚拟内存空间,文件描述符和各种句柄.单核CPU每次执行的CPU命令数为1,那么单核CPU是如何做到同时执行多条命令呢?

OS X和iOS的核心XNU内存在发生操作系统事件时(如每隔一定时间,唤起系统调用等)会切换执行路径.执行路径中的状态,例如CPU的寄存器状态等信息会保存到各自专用的内存块中,从切换目标路径到专用的内存块中,复原CPU寄存器信息,继续执行切换路径的CPU命令列.称之为"上下文切换".

由于使用多线程的程序可以在在某个线程和其他线程之间反复多次进行上下文切换,因此单核CPU看起来像并列执行多个线程一样,如果是多核CPU,是真正的提供了多个CPU的执行多个线程的技术.

多线程编程中最容易出现的问题是多个线程更新相同的资源导致数据不一致(数据竞争),停止等待事件会导致多个线程相互持续等待(死锁),使用太多的线程会消耗大量的内存.多线程能够保证应用程序的响应性能.

基础知识

GCD编程中只需要将执行的任务加入Dispatch Queue中即可,Dispatch Queue按照添加的顺序FIFO(First-In-First-Out)先入先出的规则执行处理.Dispatch Queue有两种类型串行队列(Serial Dispatch Queue)和并行队列(Concurrent Dispatch Queue) .

串行队列使用一个线程执行任务,等待上一个任务执行完成之后执行下一个任务.并行队列会使用多个线程执行任务,不需要等待之前的任务是否完成.iOS 和 OS X的核心-XNU内核决定应当使用的线程数,生成需要的线程来执行处理,当处理结束,应当执行的处理数减少时,XNU内核会结束不在需要的线程.

GCD中dispatch_get_main_queue获得主线程中执行的队列,因为主线程只有一个,所以主队列是串行列.

dispatch_get_global_queue是所有应用程序都能创建的并发队列,不需要手动创建Dispatch队列.

GCD 有两种派发方式:同步派发和异步派发,这里的同步和异步指的是 “任务派发方式”,而非任务的执行方式.

dispatch_sync定义如下:

/*!
 * @function dispatch_sync
 *
 * @abstract
 * Submits a block for synchronous execution on a dispatch queue.
 *
 * @discussion
 * Submits a block to a dispatch queue like dispatch_async(), however
 * dispatch_sync() will not return until the block has finished.
 *
 * Calls to dispatch_sync() targeting the current queue will result
 * in dead-lock. Use of dispatch_sync() is also subject to the same
 * multi-party dead-lock problems that may result from the use of a mutex.
 * Use of dispatch_async() is preferred.
 *
 * Unlike dispatch_async(), no retain is performed on the target queue. Because
 * calls to this function are synchronous, the dispatch_sync() "borrows" the
 * reference of the caller.
 *
 * As an optimization, dispatch_sync() invokes the block on the current
 * thread when possible.
 *
 * @param queue
 * The target dispatch queue to which the block is submitted.
 * The result of passing NULL in this parameter is undefined.
 *
 * @param block
 * The block to be invoked on the target dispatch queue.
 * The result of passing NULL in this parameter is undefined.
 */
#ifdef __BLOCKS__
__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)
DISPATCH_EXPORT DISPATCH_NONNULL_ALL DISPATCH_NOTHROW
void
dispatch_sync(dispatch_queue_t queue, DISPATCH_NOESCAPE dispatch_block_t block);
#endif
  • 将block的中的任务同步提交给目标Queue执行.
  • 阻塞当前Queue,执行block任务,回调当前Queue.

这就很容易解释设置dispatch_sync的队列为当前Queue发生死锁的原因,调用dispatch_sync会阻塞主队列,block无法执行,不会回调主队列.下面的代码是无法运行的:

    dispatch_sync(dispatch_get_main_queue(), ^{
        NSLog(@"FlyElephant---执行了");
    });

dispatch_async与dispatch_sync最大不同的是不会阻塞当前队列:

  • 将block的中的任务同步提交给目标Queue执行.
  • 不阻塞当前Queue,执行block任务,回调当前Queue.
dispatch_async(dispatch_get_main_queue(), ^{
        for (NSInteger i=0; i < 20; i++) {
            NSLog(@"FlyLElephant---异步:%ld",i);
        }
    });
    
    dispatch_sync(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"同步数据");
    });

并行与串行(主线程是串行队列,dispatch_get_global_queue获取对全局队列是并行队列):

dispatch_queue_t serialQueue = dispatch_queue_create("com.flyelephant.wwww", DISPATCH_QUEUE_SERIAL);
    
    dispatch_queue_t concurrentQueue = dispatch_queue_create("com.flyelephant.www", DISPATCH_QUEUE_CONCURRENT);

全局队列有四个优先级High,Default,Low和Background:

#define DISPATCH_QUEUE_PRIORITY_HIGH 2
#define DISPATCH_QUEUE_PRIORITY_DEFAULT 0
#define DISPATCH_QUEUE_PRIORITY_LOW (-2)
#define DISPATCH_QUEUE_PRIORITY_BACKGROUND INT16_MIN

串行和并行执行顺序:

    dispatch_queue_t serialQueue = dispatch_queue_create("com.flyelephant.wwww", DISPATCH_QUEUE_SERIAL);
    
    dispatch_async(serialQueue, ^{
        NSLog(@"Serial--1");
    });
    
    dispatch_async(serialQueue, ^{
        NSLog(@"Serial--2");
    });
    
    dispatch_async(serialQueue, ^{
        NSLog(@"Serial--3");
    });
    
    dispatch_async(serialQueue, ^{
        NSLog(@"Serial--4");
    });
    
    
    dispatch_queue_t concurrentQueue = dispatch_queue_create("com.flyelephant.www", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_async(concurrentQueue, ^{
        NSLog(@"Concurrent--1");
    });
    
    dispatch_async(concurrentQueue, ^{
        NSLog(@"Concurrent--2");
    });
    
    dispatch_async(concurrentQueue, ^{
        NSLog(@"Concurrent--3");
    });
    
    dispatch_async(concurrentQueue, ^{
        NSLog(@"Concurrent--4");
    });
FlyElephant.png

dispatch_set_target_queue

dispatch_set_target_queue除了能用来设置队列的优先级之外,还能够创建队列的层次体系,将不同异步任务设置为目标队列.

    dispatch_queue_t targetQueue = dispatch_queue_create("targetQueue", DISPATCH_QUEUE_SERIAL);//目标队列
    dispatch_queue_t serialQueue = dispatch_queue_create("queue1", DISPATCH_QUEUE_SERIAL);//串行队列
    dispatch_queue_t conQueue = dispatch_queue_create("queue1", DISPATCH_QUEUE_CONCURRENT);//并发队列

    dispatch_set_target_queue(serialQueue, targetQueue);
    dispatch_set_target_queue(conQueue, targetQueue);
    
    dispatch_async(serialQueue, ^{
        NSLog(@"FlyElephant---任务1 开始");
        [NSThread sleepForTimeInterval:3.f];
        NSLog(@"FlyElephant---任务1 结束");
    });
    
    dispatch_async(conQueue, ^{
        NSLog(@"FlyElephant---任务2 开始");
        [NSThread sleepForTimeInterval:2.f];
        NSLog(@"FlyElephant---任务2 结束");
    });
    
    dispatch_async(conQueue, ^{
        NSLog(@"FlyElephant---任务3 开始");
        [NSThread sleepForTimeInterval:1.f];
        NSLog(@"FlyElephant---任务3 结束");
    });
FlyElephant.png

dispatch_after延迟执行

dispatch_after只是延时提交block,不是延时立刻执行.

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"延迟执行");
    });

dispatch_barrier_async

dispatch_barrier_async函数类似于多线程中国栅栏的作用,它等待所有位于barrier函数之前的操作执行完毕后执行,并且在barrier函数执行之后,barrier函数之后的操作才会得到执行,该函数需要同dispatch_queue_create函数生成的concurrent Dispatch Queue队列一起使用.

dispatch_queue_t concurrentQueue = dispatch_queue_create("com.barrier.queue", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_async(concurrentQueue, ^(){
        NSLog(@"FlyElephant-1");
    });
    
    dispatch_async(concurrentQueue, ^(){
        NSLog(@"FlyElephant-2");
    });
    
    dispatch_async(concurrentQueue, ^(){
        NSLog(@"FlyElephant-3");
    });
    
    dispatch_barrier_async(concurrentQueue, ^(){
        NSLog(@"FlyElephant---dispatch_barrier_async");
    });
    
    dispatch_async(concurrentQueue, ^(){
        NSLog(@"FlyElephant-4");
    });
    
    dispatch_async(concurrentQueue, ^(){
        NSLog(@"FlyElephant-5");
    });
    
    dispatch_async(concurrentQueue, ^(){
        NSLog(@"FlyElephant-6");
    });
FlyElephant.png

dispatch_apply

dispatch_apply类似一个for循环,会在指定的dispatch queue中运行block任务n次,如果队列是并发队列,则会并发执行block任务,dispatch_apply是一个同步调用,block任务执行n次后才返回.dispatch_apply会将Block任务执行完成之后才会继续往下执行.

dispatch_queue_t queue = dispatch_queue_create("com.flyelephant.www", DISPATCH_QUEUE_CONCURRENT);
    dispatch_apply(10, queue, ^(size_t i) {
        NSLog(@"并行执行---%ld",i);
    });
    NSLog(@"FlyElephant---执行完成");
    
    
    dispatch_queue_t serialQueue = dispatch_queue_create("com.flyelephant.www", DISPATCH_QUEUE_SERIAL);
    dispatch_apply(10, serialQueue, ^(size_t i) {
        NSLog(@"串行执行---%ld",i);
    });
    NSLog(@"FlyElephant---执行完成");
FlyElephant.png

dispatch_once

dispatch_once只执行一次,单例实现中使用dispatch_once比较常见.

static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
    });

dispatch_group_t

dispatch_group_t创建一个队列组,dispatch_group_wait表示等待group设置的时间,dispatch_group_notify是在所有的queue任务完成之后执行notify里面的代码.

dispatch_queue_t dispatchQueue =  dispatch_queue_create("com.group.queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t dispatchGroup = dispatch_group_create();
    
    dispatch_group_async(dispatchGroup, dispatchQueue, ^{
        NSLog(@"FlyElephant---任务1完成");
    });
    
    dispatch_group_async(dispatchGroup, dispatchQueue, ^{
        sleep(3);
        NSLog(@"FlyElephant---任务2完成");
    });
    
    dispatch_group_notify(dispatchGroup, dispatchQueue, ^{
        NSLog(@"dispatch_group_notify 执行");
    });
    
    dispatch_group_async(dispatchGroup, dispatchQueue, ^{
        dispatch_group_wait(dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC));
        NSLog(@"dispatch_group_wait 结束");
    });
FlyElephant.png

可以将wait的时间设置一直等待,dispatch_group_wait会阻塞当前线程(所以不能放在主线程调用)一直等待,当group上任务完成,或者等待时间超过设置的超时时间会结束等待.

dispatch_queue_t dispatchQueue =  dispatch_queue_create("com.group.queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t dispatchGroup = dispatch_group_create();
    
    dispatch_group_async(dispatchGroup, dispatchQueue, ^{
        NSLog(@"FlyElephant---任务1完成");
    });
    
    dispatch_group_async(dispatchGroup, dispatchQueue, ^{
        sleep(3);
        NSLog(@"FlyElephant---任务2完成");
    });
    
    dispatch_group_async(dispatchGroup, dispatchQueue, ^{
        NSLog(@"FlyElephant---任务3完成");
    });
    
    dispatch_group_wait(dispatchGroup, DISPATCH_TIME_FOREVER);
    NSLog(@"dispatch_group_wait 结束");


    dispatch_group_async(dispatchGroup, dispatchQueue, ^{;
        NSLog(@"FlyElephant---任务4完成");
    });
    
    dispatch_group_async(dispatchGroup, dispatchQueue, ^{
        NSLog(@"FlyElephant---任务5完成");
    });
FlyElephant.png

dispatch_group_enter与dispatch_group_leave表示加入任务组和离开任务组,两者要同时出现,不然会出现崩溃.

dispatch_queue_t dispatchQueue =  dispatch_queue_create("com.group.queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t dispatchGroup = dispatch_group_create();
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    
    dispatch_group_enter(dispatchGroup);
    
    dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
        dispatch_async(globalQueue, ^{
            sleep(2);
            NSLog(@"FlyElephant---任务1完成");
            dispatch_group_leave(dispatchGroup);
        });
    });
    
    dispatch_group_enter(dispatchGroup);
    
    dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
        dispatch_async(globalQueue, ^{
            sleep(1);
            NSLog(@"FlyElephant---任务2完成");
            dispatch_group_leave(dispatchGroup);
        });
    });
    
    dispatch_group_enter(dispatchGroup);
    
    dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
        dispatch_async(globalQueue, ^{
            NSLog(@"FlyElephant---任务3完成");
            dispatch_group_leave(dispatchGroup);
        });
    });
    
    dispatch_group_notify(dispatchGroup, dispatchQueue, ^{
        NSLog(@"FlyElephant---dispatch_group_notify任务完成");
    });

所有的任务执行完成之后执行通知:


FlyElephant.png

如果不加入enter和leave,看下效果:

dispatch_queue_t dispatchQueue = dispatch_queue_create("com.group.www", DISPATCH_QUEUE_CONCURRENT);
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_group_t dispatchGroup = dispatch_group_create();
    
    dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
        dispatch_async(globalQueue, ^{
            sleep(2);
            NSLog(@"FlyElephant---任务1完成");
        });
    });
    
    dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
        dispatch_async(globalQueue, ^{
            sleep(3);
            NSLog(@"FlyElephant---任务2完成");
        });
    });
    
    dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){
       NSLog(@"FlyElephant---dispatch_group_notify");
    });
FlyElephant.png

dispatch_semaphore_t

dispatch_semaphore_t是一种保护线程同步的机制,使用dispatch_semaphore_signal加1,dispatch_semaphore_wait减1,为0的时候等待的设置方式来达到线程同步的目的和同步锁一样能够解决资源抢占的问题.

dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
    
    self.data  = [[NSMutableArray alloc] init];
    
    for (NSInteger i = 0; i < 10; i++) {
        
        dispatch_async(queue, ^(){
            
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            
            [self.data addObject:[NSString stringWithFormat:@"FlyElephant---%ld",i]];
            
            dispatch_semaphore_signal(semaphore);
            
        });
    }
FlyElephant.png

参考资料:
官方文档
线程到底是什么?

推荐阅读更多精彩内容

  • 多线程 在iOS开发中为提高程序的运行效率会将比较耗时的操作放在子线程中执行,iOS系统进程默认启动一个主线程,用...
    郭豪豪阅读 1,224评论 0赞 4
  • GCD (Grand Central Dispatch) :iOS4 开始引入,使用更加方便,程序员只需要将任务添...
    池鹏程阅读 408评论 0赞 2
  • iOS多线程之GCD 什么是GCD GCD(grand central dispatch) 是 libdispat...
    comst阅读 578评论 0赞 0
  • 原创文章 转载请注明出处, 谢谢! (~ o ~)Y 本文思维导图 GCD是什么 全称是 Grand Centra...
    Jimmy_P阅读 3,811评论 10赞 63
  • 床上,左侧卧,左手缩怀里,手腕塞右腋窝下。身上盖了两床被子,露出头和右手。地球引力把脸压紧在枕头上。脸陷得深了,只...
    阿部岱谛阅读 3,579评论 1赞 1