iOS實(shí)現(xiàn)多線程編程有四種方式Pthreads苍凛,NSThread姆另,NSOperation & NSOperationQueue和GCD.GCD(Grand Central Dispatch)是異步執(zhí)行任務(wù)的技術(shù)之一搀暑,一般將應(yīng)用程序中線程管理代碼在系統(tǒng)級(jí)實(shí)現(xiàn).開發(fā)過程中只需要定義想執(zhí)行的任務(wù)并追加到適當(dāng)?shù)腄ispatch Queue,GCD就能生成必要的線程執(zhí)行任務(wù).
GCD以其難以置信的API風(fēng)格铅搓,實(shí)現(xiàn)了極其復(fù)雜繁瑣的多線程編程舞竿,是多線程編程中必不可少一把利劍.GCD屬于系統(tǒng)級(jí)的線程管理,GCD中的FIFO隊(duì)列稱為dispatch queue,用來保證先進(jìn)來的任務(wù)先得到執(zhí)行.
基礎(chǔ)概念
進(jìn)程是一個(gè)正在執(zhí)行程序的實(shí)例赵抢,在iOS中可以理解為一個(gè)正在運(yùn)行App剧蹂,每個(gè)進(jìn)程都有一個(gè)單獨(dú)的Process ID(進(jìn)程ID).現(xiàn)在操作系統(tǒng)將線程作為基本的操作單元,線程是一組寄存器的狀態(tài)烦却,一個(gè)進(jìn)程包含了多個(gè)線程.一個(gè)進(jìn)程內(nèi)的所有線程都共享虛擬內(nèi)存空間宠叼,文件描述符和各種句柄.單核CPU每次執(zhí)行的CPU命令數(shù)為1,那么單核CPU是如何做到同時(shí)執(zhí)行多條命令呢其爵?
OS X和iOS的核心XNU內(nèi)存在發(fā)生操作系統(tǒng)事件時(shí)(如每隔一定時(shí)間冒冬,喚起系統(tǒng)調(diào)用等)會(huì)切換執(zhí)行路徑.執(zhí)行路徑中的狀態(tài),例如CPU的寄存器狀態(tài)等信息會(huì)保存到各自專用的內(nèi)存塊中摩渺,從切換目標(biāo)路徑到專用的內(nèi)存塊中简烤,復(fù)原CPU寄存器信息,繼續(xù)執(zhí)行切換路徑的CPU命令列.稱之為"上下文切換".
由于使用多線程的程序可以在在某個(gè)線程和其他線程之間反復(fù)多次進(jìn)行上下文切換证逻,因此單核CPU看起來像并列執(zhí)行多個(gè)線程一樣乐埠,如果是多核CPU抗斤,是真正的提供了多個(gè)CPU的執(zhí)行多個(gè)線程的技術(shù).
多線程編程中最容易出現(xiàn)的問題是多個(gè)線程更新相同的資源導(dǎo)致數(shù)據(jù)不一致(數(shù)據(jù)競爭)囚企,停止等待事件會(huì)導(dǎo)致多個(gè)線程相互持續(xù)等待(死鎖),使用太多的線程會(huì)消耗大量的內(nèi)存.多線程能夠保證應(yīng)用程序的響應(yīng)性能.
基礎(chǔ)知識(shí)
GCD編程中只需要將執(zhí)行的任務(wù)加入Dispatch Queue中即可瑞眼,Dispatch Queue按照添加的順序FIFO(First-In-First-Out)先入先出的規(guī)則執(zhí)行處理.Dispatch Queue有兩種類型串行隊(duì)列(Serial Dispatch Queue)和并行隊(duì)列(Concurrent Dispatch Queue) .
串行隊(duì)列使用一個(gè)線程執(zhí)行任務(wù)龙宏,等待上一個(gè)任務(wù)執(zhí)行完成之后執(zhí)行下一個(gè)任務(wù).并行隊(duì)列會(huì)使用多個(gè)線程執(zhí)行任務(wù),不需要等待之前的任務(wù)是否完成.iOS 和 OS X的核心-XNU內(nèi)核決定應(yīng)當(dāng)使用的線程數(shù)伤疙,生成需要的線程來執(zhí)行處理银酗,當(dāng)處理結(jié)束,應(yīng)當(dāng)執(zhí)行的處理數(shù)減少時(shí)徒像,XNU內(nèi)核會(huì)結(jié)束不在需要的線程.
GCD中dispatch_get_main_queue獲得主線程中執(zhí)行的隊(duì)列黍特,因?yàn)橹骶€程只有一個(gè),所以主隊(duì)列是串行列.
dispatch_get_global_queue是所有應(yīng)用程序都能創(chuàng)建的并發(fā)隊(duì)列锯蛀,不需要手動(dòng)創(chuàng)建Dispatch隊(duì)列.
GCD 有兩種派發(fā)方式:同步派發(fā)和異步派發(fā)灭衷,這里的同步和異步指的是 “任務(wù)派發(fā)方式”,而非任務(wù)的執(zhí)行方式.
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的中的任務(wù)同步提交給目標(biāo)Queue執(zhí)行.
- 阻塞當(dāng)前Queue旁涤,執(zhí)行block任務(wù)翔曲,回調(diào)當(dāng)前Queue.
這就很容易解釋設(shè)置dispatch_sync的隊(duì)列為當(dāng)前Queue發(fā)生死鎖的原因,調(diào)用dispatch_sync會(huì)阻塞主隊(duì)列劈愚,block無法執(zhí)行瞳遍,不會(huì)回調(diào)主隊(duì)列.下面的代碼是無法運(yùn)行的:
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"FlyElephant---執(zhí)行了");
});
dispatch_async與dispatch_sync最大不同的是不會(huì)阻塞當(dāng)前隊(duì)列:
- 將block的中的任務(wù)同步提交給目標(biāo)Queue執(zhí)行.
- 不阻塞當(dāng)前Queue,執(zhí)行block任務(wù)菌羽,回調(diào)當(dāng)前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(@"同步數(shù)據(jù)");
});
并行與串行(主線程是串行隊(duì)列掠械,dispatch_get_global_queue獲取對全局隊(duì)列是并行隊(duì)列):
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);
全局隊(duì)列有四個(gè)優(yōu)先級(jí)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
串行和并行執(zhí)行順序:
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");
});
dispatch_set_target_queue
dispatch_set_target_queue除了能用來設(shè)置隊(duì)列的優(yōu)先級(jí)之外份蝴,還能夠創(chuàng)建隊(duì)列的層次體系犁功,將不同異步任務(wù)設(shè)置為目標(biāo)隊(duì)列.
dispatch_queue_t targetQueue = dispatch_queue_create("targetQueue", DISPATCH_QUEUE_SERIAL);//目標(biāo)隊(duì)列
dispatch_queue_t serialQueue = dispatch_queue_create("queue1", DISPATCH_QUEUE_SERIAL);//串行隊(duì)列
dispatch_queue_t conQueue = dispatch_queue_create("queue1", DISPATCH_QUEUE_CONCURRENT);//并發(fā)隊(duì)列
dispatch_set_target_queue(serialQueue, targetQueue);
dispatch_set_target_queue(conQueue, targetQueue);
dispatch_async(serialQueue, ^{
NSLog(@"FlyElephant---任務(wù)1 開始");
[NSThread sleepForTimeInterval:3.f];
NSLog(@"FlyElephant---任務(wù)1 結(jié)束");
});
dispatch_async(conQueue, ^{
NSLog(@"FlyElephant---任務(wù)2 開始");
[NSThread sleepForTimeInterval:2.f];
NSLog(@"FlyElephant---任務(wù)2 結(jié)束");
});
dispatch_async(conQueue, ^{
NSLog(@"FlyElephant---任務(wù)3 開始");
[NSThread sleepForTimeInterval:1.f];
NSLog(@"FlyElephant---任務(wù)3 結(jié)束");
});
dispatch_after延遲執(zhí)行
dispatch_after只是延時(shí)提交block,不是延時(shí)立刻執(zhí)行.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"延遲執(zhí)行");
});
dispatch_barrier_async
dispatch_barrier_async函數(shù)類似于多線程中國柵欄的作用,它等待所有位于barrier函數(shù)之前的操作執(zhí)行完畢后執(zhí)行,并且在barrier函數(shù)執(zhí)行之后,barrier函數(shù)之后的操作才會(huì)得到執(zhí)行,該函數(shù)需要同dispatch_queue_create函數(shù)生成的concurrent Dispatch Queue隊(duì)列一起使用.
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");
});
dispatch_apply
dispatch_apply類似一個(gè)for循環(huán)婚夫,會(huì)在指定的dispatch queue中運(yùn)行block任務(wù)n次浸卦,如果隊(duì)列是并發(fā)隊(duì)列,則會(huì)并發(fā)執(zhí)行block任務(wù)案糙,dispatch_apply是一個(gè)同步調(diào)用限嫌,block任務(wù)執(zhí)行n次后才返回.dispatch_apply會(huì)將Block任務(wù)執(zhí)行完成之后才會(huì)繼續(xù)往下執(zhí)行.
dispatch_queue_t queue = dispatch_queue_create("com.flyelephant.www", DISPATCH_QUEUE_CONCURRENT);
dispatch_apply(10, queue, ^(size_t i) {
NSLog(@"并行執(zhí)行---%ld",i);
});
NSLog(@"FlyElephant---執(zhí)行完成");
dispatch_queue_t serialQueue = dispatch_queue_create("com.flyelephant.www", DISPATCH_QUEUE_SERIAL);
dispatch_apply(10, serialQueue, ^(size_t i) {
NSLog(@"串行執(zhí)行---%ld",i);
});
NSLog(@"FlyElephant---執(zhí)行完成");
dispatch_once
dispatch_once只執(zhí)行一次,單例實(shí)現(xiàn)中使用dispatch_once比較常見.
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
});
dispatch_group_t
dispatch_group_t創(chuàng)建一個(gè)隊(duì)列組时捌,dispatch_group_wait表示等待group設(shè)置的時(shí)間怒医,dispatch_group_notify是在所有的queue任務(wù)完成之后執(zhí)行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---任務(wù)1完成");
});
dispatch_group_async(dispatchGroup, dispatchQueue, ^{
sleep(3);
NSLog(@"FlyElephant---任務(wù)2完成");
});
dispatch_group_notify(dispatchGroup, dispatchQueue, ^{
NSLog(@"dispatch_group_notify 執(zhí)行");
});
dispatch_group_async(dispatchGroup, dispatchQueue, ^{
dispatch_group_wait(dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC));
NSLog(@"dispatch_group_wait 結(jié)束");
});
可以將wait的時(shí)間設(shè)置一直等待,dispatch_group_wait會(huì)阻塞當(dāng)前線程(所以不能放在主線程調(diào)用)一直等待奢讨,當(dāng)group上任務(wù)完成稚叹,或者等待時(shí)間超過設(shè)置的超時(shí)時(shí)間會(huì)結(jié)束等待.
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---任務(wù)1完成");
});
dispatch_group_async(dispatchGroup, dispatchQueue, ^{
sleep(3);
NSLog(@"FlyElephant---任務(wù)2完成");
});
dispatch_group_async(dispatchGroup, dispatchQueue, ^{
NSLog(@"FlyElephant---任務(wù)3完成");
});
dispatch_group_wait(dispatchGroup, DISPATCH_TIME_FOREVER);
NSLog(@"dispatch_group_wait 結(jié)束");
dispatch_group_async(dispatchGroup, dispatchQueue, ^{;
NSLog(@"FlyElephant---任務(wù)4完成");
});
dispatch_group_async(dispatchGroup, dispatchQueue, ^{
NSLog(@"FlyElephant---任務(wù)5完成");
});
dispatch_group_enter與dispatch_group_leave表示加入任務(wù)組和離開任務(wù)組,兩者要同時(shí)出現(xiàn)拿诸,不然會(huì)出現(xiàn)崩潰.
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---任務(wù)1完成");
dispatch_group_leave(dispatchGroup);
});
});
dispatch_group_enter(dispatchGroup);
dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
dispatch_async(globalQueue, ^{
sleep(1);
NSLog(@"FlyElephant---任務(wù)2完成");
dispatch_group_leave(dispatchGroup);
});
});
dispatch_group_enter(dispatchGroup);
dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
dispatch_async(globalQueue, ^{
NSLog(@"FlyElephant---任務(wù)3完成");
dispatch_group_leave(dispatchGroup);
});
});
dispatch_group_notify(dispatchGroup, dispatchQueue, ^{
NSLog(@"FlyElephant---dispatch_group_notify任務(wù)完成");
});
所有的任務(wù)執(zhí)行完成之后執(zhí)行通知:
如果不加入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---任務(wù)1完成");
});
});
dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
dispatch_async(globalQueue, ^{
sleep(3);
NSLog(@"FlyElephant---任務(wù)2完成");
});
});
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){
NSLog(@"FlyElephant---dispatch_group_notify");
});
dispatch_semaphore_t
dispatch_semaphore_t是一種保護(hù)線程同步的機(jī)制,使用dispatch_semaphore_signal加1亩码,dispatch_semaphore_wait減1季率,為0的時(shí)候等待的設(shè)置方式來達(dá)到線程同步的目的和同步鎖一樣能夠解決資源搶占的問題.
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);
});
}