GCD基本功能小结

2017-05-07  本文已影响23人  Daved

GCD缘起

GCD(Grand Central Dispatch) 是 Apple 开发的一个基于C的并发编程解决方案,为代码在iOS和OS X的多核硬件上执行提供支持。该方案在 Mac OS X 10.6 雪豹中首次推出,并随后被引入到了 iOS4.0 中。使用者不需要编写任何线程管理代码,GCD底层实现了线程相关生命周期的管理工作(创建、调度、销毁等)。

核心概念

任务:一段基于Block的代码,将要使用GCD来执行该段代码。
队列:按照FIFO(First In First Out)的方式调度任务在哪一个线程上执行。GCD包括以下几种队列。

基本使用

获取队列

dispatch_queue_t queue = dispatch_queue_create("com.example.mySerialQueue", DISPATCH_QUEUE_SERIAL);
// 或者如下方式
dispatch_queue_t queue = dispatch_queue_create("com.example.mySerialQueue", NULL);
dispatch_queue_t queue = dispatch_queue_create("com.example.myConcrrentQueue", DISPATCH_QUEUE_CONCURRENT);

执行任务

同步方式

任务被添加到队列后会在任务调用上下文线程中执行,不会开启新线程。

{
dispatch_queue_t queue = dispatch_queue_create("com.example.serial", DISPATCH_QUEUE_SERIAL);

NSLog(@"start!!");
dispatch_sync(queue, ^{
    NSLog(@"work thread:%@", [NSThread currentThread]);
});

NSLog(@"end!!");

}
```

在子线程中调用

```
dispatch_queue_t queue = dispatch_queue_create("com.example.concurrent", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
    NSLog(@"current thread:%@", [NSThread currentThread]);
    [self gcdSyncSerail];
});
```
运行结果

```

2017-xx-xx xx:xx:xx.496 current thread:<NSThread: 0x608000261bc0>{number = 3, name = (null)}
2017-xx-xx xx:xx:xx.497 start!!
2017-xx-xx xx:xx:xx.498 work thread:<NSThread: 0x608000261bc0>{number = 3, name = (null)}
2017-xx-xx xx:xx:xx.498 end!!
```

在*主线程*调用运行结果如下

```

2017-xx-xx xx:xx:xx.496 current thread:<NSThread: 0x600000078780>{number = 1, name = main}
2017-xx-xx xx:xx:xx.497 start!!
2017-xx-xx xx:xx:xx.498 work thread:<NSThread: 0x600000078780>{number = 1, name = main}
2017-xx-xx xx:xx:xx.498 end!!
```

异步方式

任务被添加到队列后会开启新线程来执行,开启线程数量由GCD来控制,目前尚无相关API来设置。

2017-xx-xx xx:xx:xx.096 begin!!
2017-xx-xx xx:xx:xx.096 end!!
2017-xx-xx xx:xx:xx.097 <NSThread: 0x600000268b40>{number = 1, name = main} 0
2017-xx-xx xx:xx:xx.097 <NSThread: 0x60800007cdc0>{number = 1, name = main} 1
2017-xx-xx xx:xx:xx.097 <NSThread: 0x608000077d40>{number = 1, name = main} 2
2017-xx-xx xx:xx:xx.098 <NSThread: 0x600000268c00>{number = 1, name = main} 3

核心功能应用

利用同步任务建立任务之间的 依赖关系

例如:有3个任务A、B、C,任务B、C需要在任务A执行完成后才可以开始执行。

dispatch_queue_t  queue = dispatch_queue_create("com.example.concurrent", DISPATCH_QUEUE_CONCURRENT);
    
    // 同步任务,需要马上执行。 不开启新线程
    dispatch_sync(queue, ^{
        NSLog(@"Task A %@", [NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"TASK B %@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"TASK C %@", [NSThread currentThread]);
    });

运行结果

2017-xx-xx xx:xx:xx.097 Task A :<NSThread: 0x60000006c2c0>{number = 1, name = main}
2017-xx-xx xx:xx:xx.097 Task B :<NSThread: 0x60000007ed80>{number = 3, name = (null)}
2017-xx-xx xx:xx:xx.097 Task C :<NSThread: 0x60000007e9c0>{number = 4, name = (null)

线程间通信

一种GCD典型的使用方式是使用异步任务并发队列执行耗时操作,在主队列中执行更新UI相关操作。

 dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        NSURL *url = [NSURL URLWithString:@"http://xxx.xxx.com/xxx.jpg"];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.iconView.image = image;
            NSLog(@"%@", [NSThread currentThread]);
            //由上文异步->主队列执行方式可知,此时所处线程为主线程
        });
    });

队列选择

队列选择可以从以下几个方面进行权衡

通过以上的介绍,我们现在已经掌握了GCD核心基本功能的使用以及各种使用方式之间的差异、如何选择合适的API。接下来介绍一下GCD常见的其它使用方式。

其它使用方式

dispatch_once

dispatch_once能保证相关代码片段在程序生命周期中只被执行一次,该方法是线程安全的。dispatch_once常被用于单例模式实现。

+(Singleton *)sharedInstance  
{  
    static Singleton *singleton = nil;  
      
    static dispatch_once_t onceToken;  
    dispatch_once(&onceToken, ^{  
        sharedManager = [[Singleton alloc] init];  
    });  
      
    return singleton;  
}

dispatch_after

dispatch_after延时执行,使用方式如下。

 dispatch_time_t seconds = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
    
    dispatch_after(seconds, dispatch_get_main_queue(), ^{
            //TODO 
    });
    

另一种延时实现,使用NSObject类的- performSelector:withObject:afterDelay:方法。

dispatch_group

dispatch_group适用于对多个耗时操作执行完毕后再统一做处理的应用场景,例如:有A、B、C三个下载任务,在所有下载完成后通知用户进行后续操作。

dispatch_group_t group = dispatch_group_create();

    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    
    dispatch_group_async(group, queue, ^{
        NSLog(@"Task A:---%@", [NSThread currentThread]);
    });
    
    dispatch_group_async(group, queue, ^{
        NSLog(@"Task B:---%@", [NSThread currentThread]);
    });
    
    dispatch_group_async(group, queue, ^{
        NSLog(@"Task C:---%@", [NSThread currentThread]);
    });
    
    dispatch_group_notify(group, queue, ^{
        NSLog(@"All tasks have finished:%@", [NSThread currentThread]); 
    });

运行结果

2017-xx-xx xx:xx:xx.097 Task B:---<NSThread: 0x60000007be80>{number = 4, name = (null)}
2017-xx-xx xx:xx:xx.097 Task A:---<NSThread: 0x60800007d880>{number = 3, name = (null)}
2017-xx-xx xx:xx:xx.098 Task C:---<NSThread: 0x60000007f240>{number = 5, name = (null)}
2017-xx-xx xx:xx:xx.098 All tasks have finished:<NSThread: 0x60000007f240>{number = 5, name = (null)}

dispatch_group_notify可以跨队列接收异步任务完成通知。

小结

通过本文我们了解了GCD的核心概念、队列、任务执行方式、常见使用方式以及相关应用场景等。

上一篇 下一篇

猜你喜欢

热点阅读