GCD多線程詳解

1. GCD 簡(jiǎn)介

2. GCD 任務(wù)和隊(duì)列

3. GCD 的使用步驟

4. GCD 的基本使用(6種不同組合區(qū)別)

5. GCD 線程間的通信

6. GCD 的其他方法(柵欄方法:dispatch_barrier_async、延時(shí)執(zhí)行方法:dispatch_after、一次性代碼(只執(zhí)行一次):dispatch_once、快速迭代方法:dispatch_apply、隊(duì)列組:dispatch_group、信號(hào)量:dispatch_semaphore)

1. GCD 簡(jiǎn)介

GCD 可用于多核的并行運(yùn)算

GCD 會(huì)自動(dòng)利用更多的 CPU 內(nèi)核(比如雙核、四核)

GCD 會(huì)自動(dòng)管理線程的生命周期(創(chuàng)建線程、調(diào)度任務(wù)、銷毀線程)

程序員只需要告訴 GCD 想要執(zhí)行什么任務(wù),不需要編寫(xiě)任何線程管理代碼

2. GCD 任務(wù)和隊(duì)列

學(xué)習(xí) GCD 之前,先來(lái)了解 GCD 中兩個(gè)核心概念:任務(wù)隊(duì)列

任務(wù):就是執(zhí)行操作的意思,換句話說(shuō)就是你在線程中執(zhí)行的那段代碼。在 GCD 中是放在 block 中的。執(zhí)行任務(wù)有兩種方式:同步執(zhí)行(sync)異步執(zhí)行(async)。兩者的主要區(qū)別是:是否等待隊(duì)列的任務(wù)執(zhí)行結(jié)束,以及是否具備開(kāi)啟新線程的能力。

同步執(zhí)行(sync)

同步添加任務(wù)到指定的隊(duì)列中,在添加的任務(wù)執(zhí)行結(jié)束之前,會(huì)一直等待,直到隊(duì)列里面的任務(wù)完成之后再繼續(xù)執(zhí)行。

只能在當(dāng)前線程中執(zhí)行任務(wù),不具備開(kāi)啟新線程的能力。

異步執(zhí)行(async)

異步添加任務(wù)到指定的隊(duì)列中,它不會(huì)做任何等待,可以繼續(xù)執(zhí)行任務(wù)。

可以在新的線程中執(zhí)行任務(wù),具備開(kāi)啟新線程的能力。

舉個(gè)簡(jiǎn)單例子:你要打電話給小明和小白。

同步執(zhí)行就是,你打電話給小明的時(shí)候,不能同時(shí)打給小白,等到給小明打完了,才能打給小白(等待任務(wù)執(zhí)行結(jié)束)。而且只能用當(dāng)前的電話(不具備開(kāi)啟新線程的能力)。

而異步執(zhí)行就是,你打電話給小明的時(shí)候,不等和小明通話結(jié)束,還能直接給小白打電話,不用等著和小明通話結(jié)束再打(不用等待任務(wù)執(zhí)行結(jié)束)。除了當(dāng)前電話,你還可以使用其他所能使用的電話(具備開(kāi)啟新線程的能力)。

注意:異步執(zhí)行(async)雖然具有開(kāi)啟新線程的能力,但是并不一定開(kāi)啟新線程。這跟任務(wù)所指定的隊(duì)列類型有關(guān)(下面會(huì)講)。

隊(duì)列(Dispatch Queue):這里的隊(duì)列指執(zhí)行任務(wù)的等待隊(duì)列,即用來(lái)存放任務(wù)的隊(duì)列。隊(duì)列是一種特殊的線性表,采用 FIFO(先進(jìn)先出)的原則,即新任務(wù)總是被插入到隊(duì)列的末尾,而讀取任務(wù)的時(shí)候總是從隊(duì)列的頭部開(kāi)始讀取。每讀取一個(gè)任務(wù),則從隊(duì)列中釋放一個(gè)任務(wù)。隊(duì)列的結(jié)構(gòu)可參考下圖:

隊(duì)列(Dispatch Queue).png

在 GCD 中有兩種隊(duì)列:串行隊(duì)列并發(fā)隊(duì)列。兩者都符合 FIFO(先進(jìn)先出)的原則。兩者的主要區(qū)別是:執(zhí)行順序不同,以及開(kāi)啟線程數(shù)不同。

串行隊(duì)列(Serial Dispatch Queue)

每次只有一個(gè)任務(wù)被執(zhí)行。讓任務(wù)一個(gè)接著一個(gè)地執(zhí)行。(只開(kāi)啟一個(gè)線程,一個(gè)任務(wù)執(zhí)行完畢后,再執(zhí)行下一個(gè)任務(wù))

并發(fā)隊(duì)列(Concurrent Dispatch Queue)

可以讓多個(gè)任務(wù)并發(fā)(同時(shí))執(zhí)行。(可以開(kāi)啟多個(gè)線程,并且同時(shí)執(zhí)行任務(wù))

注意:并發(fā)隊(duì)列的并發(fā)功能只有在異步(dispatch_async)函數(shù)下才有效

兩者具體區(qū)別如下兩圖所示。

串行隊(duì)列.png

并發(fā)隊(duì)列.png

3. GCD 的使用步驟

GCD 的使用步驟其實(shí)很簡(jiǎn)單,只有兩步。

創(chuàng)建一個(gè)隊(duì)列(串行隊(duì)列或并發(fā)隊(duì)列)

將任務(wù)追加到任務(wù)的等待隊(duì)列中,然后系統(tǒng)就會(huì)根據(jù)任務(wù)類型執(zhí)行任務(wù)(同步執(zhí)行或異步執(zhí)行)

下邊來(lái)看看隊(duì)列的創(chuàng)建方法/獲取方法,以及任務(wù)的創(chuàng)建方法。

3.1 隊(duì)列的創(chuàng)建方法/獲取方法

可以使用dispatch_queue_create來(lái)創(chuàng)建隊(duì)列,需要傳入兩個(gè)參數(shù),第一個(gè)參數(shù)表示隊(duì)列的唯一標(biāo)識(shí)符,用于 DEBUG,可為空,Dispatch Queue 的名稱推薦使用應(yīng)用程序 ID 這種逆序全程域名;第二個(gè)參數(shù)用來(lái)識(shí)別是串行隊(duì)列還是并發(fā)隊(duì)列。DISPATCH_QUEUE_SERIAL表示串行隊(duì)列,DISPATCH_QUEUE_CONCURRENT表示并發(fā)隊(duì)列。

// 串行隊(duì)列的創(chuàng)建方法dispatch_queue_tqueue= dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_SERIAL);// 并發(fā)隊(duì)列的創(chuàng)建方法dispatch_queue_tqueue= dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_CONCURRENT);

對(duì)于串行隊(duì)列,GCD 提供了的一種特殊的串行隊(duì)列:主隊(duì)列(Main Dispatch Queue)

所有放在主隊(duì)列中的任務(wù),都會(huì)放到主線程中執(zhí)行。

可使用dispatch_get_main_queue()獲得主隊(duì)列。

// 主隊(duì)列的獲取方法dispatch_queue_tqueue= dispatch_get_main_queue();

對(duì)于并發(fā)隊(duì)列,GCD 默認(rèn)提供了全局并發(fā)隊(duì)列(Global Dispatch Queue)

可以使用dispatch_get_global_queue來(lái)獲取。需要傳入兩個(gè)參數(shù)。第一個(gè)參數(shù)表示隊(duì)列優(yōu)先級(jí),一般用DISPATCH_QUEUE_PRIORITY_DEFAULT。第二個(gè)參數(shù)暫時(shí)沒(méi)用,用0即可。

// 全局并發(fā)隊(duì)列的獲取方法dispatch_queue_tqueue= dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);

3.2 任務(wù)的創(chuàng)建方法

GCD 提供了同步執(zhí)行任務(wù)的創(chuàng)建方法dispatch_sync和異步執(zhí)行任務(wù)創(chuàng)建方法dispatch_async。

// 同步執(zhí)行任務(wù)創(chuàng)建方法dispatch_sync(queue, ^{// 這里放同步執(zhí)行任務(wù)代碼});// 異步執(zhí)行任務(wù)創(chuàng)建方法dispatch_async(queue, ^{// 這里放異步執(zhí)行任務(wù)代碼});

雖然使用 GCD 只需兩步,但是既然我們有兩種隊(duì)列(串行隊(duì)列/并發(fā)隊(duì)列),兩種任務(wù)執(zhí)行方式(同步執(zhí)行/異步執(zhí)行),那么我們就有了四種不同的組合方式。這四種不同的組合方式是:

同步執(zhí)行 + 并發(fā)隊(duì)列

異步執(zhí)行 + 并發(fā)隊(duì)列

同步執(zhí)行 + 串行隊(duì)列

異步執(zhí)行 + 串行隊(duì)列

實(shí)際上,剛才還說(shuō)了兩種特殊隊(duì)列:全局并發(fā)隊(duì)列、主隊(duì)列。全局并發(fā)隊(duì)列可以作為普通并發(fā)隊(duì)列來(lái)使用。但是主隊(duì)列因?yàn)橛悬c(diǎn)特殊,所以我們就又多了兩種組合方式。這樣就有六種不同的組合方式了。

同步執(zhí)行 + 主隊(duì)列

異步執(zhí)行 + 主隊(duì)列

那么這幾種不同組合方式各有什么區(qū)別呢,這里為了方便,先上結(jié)果,再來(lái)講解。你可以直接查看表格結(jié)果,然后跳過(guò)4. GCD的基本使用


區(qū)別并發(fā)隊(duì)列串行隊(duì)列主隊(duì)列

同步(sync)沒(méi)有開(kāi)啟新線程,串行執(zhí)行任務(wù)沒(méi)有開(kāi)啟新線程,串行執(zhí)行任務(wù)主線程調(diào)用:死鎖卡住不執(zhí)行

其他線程調(diào)用:沒(méi)有開(kāi)啟新線程,串行執(zhí)行任務(wù)

異步(async)有開(kāi)啟新線程,并發(fā)執(zhí)行任務(wù)有開(kāi)啟新線程(1條),串行執(zhí)行任務(wù)沒(méi)有開(kāi)啟新線程,串行執(zhí)行任務(wù)

下邊我們來(lái)分別講講這幾種不同的組合方式的使用方法。

4. GCD 的基本使用

先來(lái)講講并發(fā)隊(duì)列的兩種執(zhí)行方式。

4.1 同步執(zhí)行 + 并發(fā)隊(duì)列

在當(dāng)前線程中執(zhí)行任務(wù),不會(huì)開(kāi)啟新線程,執(zhí)行完一個(gè)任務(wù),再執(zhí)行下一個(gè)任務(wù)。

/**

* 同步執(zhí)行 + 并發(fā)隊(duì)列

* 特點(diǎn):在當(dāng)前線程中執(zhí)行任務(wù),不會(huì)開(kāi)啟新線程,執(zhí)行完一個(gè)任務(wù),再執(zhí)行下一個(gè)任務(wù)。

*/- (void)syncConcurrent {NSLog(@"currentThread---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程N(yùn)SLog(@"syncConcurrent---begin");dispatch_queue_tqueue = dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_CONCURRENT);dispatch_sync(queue, ^{// 追加任務(wù)1for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"1---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });dispatch_sync(queue, ^{// 追加任務(wù)2for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"2---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });dispatch_sync(queue, ^{// 追加任務(wù)3for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"3---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });NSLog(@"syncConcurrent---end");}

輸出結(jié)果:

2018-02-23 20:34:55.095932+0800 YSC-GCD-demo[19892:4996930] currentThread---{number = 1, name = main}

2018-02-23 20:34:55.096086+0800 YSC-GCD-demo[19892:4996930] syncConcurrent---begin

2018-02-23 20:34:57.097589+0800 YSC-GCD-demo[19892:4996930] 1---{number = 1, name = main}

2018-02-23 20:34:59.099100+0800 YSC-GCD-demo[19892:4996930] 1---{number = 1, name = main}

2018-02-23 20:35:01.099843+0800 YSC-GCD-demo[19892:4996930] 2---{number = 1, name = main}

2018-02-23 20:35:03.101171+0800 YSC-GCD-demo[19892:4996930] 2---{number = 1, name = main}

2018-02-23 20:35:05.101750+0800 YSC-GCD-demo[19892:4996930] 3---{number = 1, name = main}

2018-02-23 20:35:07.102414+0800 YSC-GCD-demo[19892:4996930] 3---{number = 1, name = main}

2018-02-23 20:35:07.102575+0800 YSC-GCD-demo[19892:4996930] syncConcurrent---end

從同步執(zhí)行 + 并發(fā)隊(duì)列中可看到:

所有任務(wù)都是在當(dāng)前線程(主線程)中執(zhí)行的,沒(méi)有開(kāi)啟新的線程(同步執(zhí)行不具備開(kāi)啟新線程的能力)。

所有任務(wù)都在打印的syncConcurrent---begin和syncConcurrent---end之間執(zhí)行的(同步任務(wù)需要等待隊(duì)列的任務(wù)執(zhí)行結(jié)束)。

任務(wù)按順序執(zhí)行的。按順序執(zhí)行的原因:雖然并發(fā)隊(duì)列可以開(kāi)啟多個(gè)線程,并且同時(shí)執(zhí)行多個(gè)任務(wù)。但是因?yàn)楸旧聿荒軇?chuàng)建新線程,只有當(dāng)前線程這一個(gè)線程(同步任務(wù)不具備開(kāi)啟新線程的能力),所以也就不存在并發(fā)。而且當(dāng)前線程只有等待當(dāng)前隊(duì)列中正在執(zhí)行的任務(wù)執(zhí)行完畢之后,才能繼續(xù)接著執(zhí)行下面的操作(同步任務(wù)需要等待隊(duì)列的任務(wù)執(zhí)行結(jié)束)。所以任務(wù)只能一個(gè)接一個(gè)按順序執(zhí)行,不能同時(shí)被執(zhí)行。

4.2 異步執(zhí)行 + 并發(fā)隊(duì)列

可以開(kāi)啟多個(gè)線程,任務(wù)交替(同時(shí))執(zhí)行。

/**

* 異步執(zhí)行 + 并發(fā)隊(duì)列

* 特點(diǎn):可以開(kāi)啟多個(gè)線程,任務(wù)交替(同時(shí))執(zhí)行。

*/- (void)asyncConcurrent {NSLog(@"currentThread---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程N(yùn)SLog(@"asyncConcurrent---begin");dispatch_queue_tqueue = dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_CONCURRENT);dispatch_async(queue, ^{// 追加任務(wù)1for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"1---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });dispatch_async(queue, ^{// 追加任務(wù)2for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"2---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });dispatch_async(queue, ^{// 追加任務(wù)3for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"3---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });NSLog(@"asyncConcurrent---end");}

輸出結(jié)果:

2018-02-23 20:36:41.769269+0800 YSC-GCD-demo[19929:5005237] currentThread---{number = 1, name = main}

2018-02-23 20:36:41.769496+0800 YSC-GCD-demo[19929:5005237] asyncConcurrent---begin

2018-02-23 20:36:41.769725+0800 YSC-GCD-demo[19929:5005237] asyncConcurrent---end

2018-02-23 20:36:43.774442+0800 YSC-GCD-demo[19929:5005566] 2---{number = 5, name = (null)}

2018-02-23 20:36:43.774440+0800 YSC-GCD-demo[19929:5005567] 3---{number = 4, name = (null)}

2018-02-23 20:36:43.774440+0800 YSC-GCD-demo[19929:5005565] 1---{number = 3, name = (null)}

2018-02-23 20:36:45.779286+0800 YSC-GCD-demo[19929:5005567] 3---{number = 4, name = (null)}

2018-02-23 20:36:45.779302+0800 YSC-GCD-demo[19929:5005565] 1---{number = 3, name = (null)}

2018-02-23 20:36:45.779286+0800 YSC-GCD-demo[19929:5005566] 2---{number = 5, name = (null)}

在異步執(zhí)行 + 并發(fā)隊(duì)列中可以看出:

除了當(dāng)前線程(主線程),系統(tǒng)又開(kāi)啟了3個(gè)線程,并且任務(wù)是交替/同時(shí)執(zhí)行的。(異步執(zhí)行具備開(kāi)啟新線程的能力。且并發(fā)隊(duì)列可開(kāi)啟多個(gè)線程,同時(shí)執(zhí)行多個(gè)任務(wù))。

所有任務(wù)是在打印的syncConcurrent---begin和syncConcurrent---end之后才執(zhí)行的。說(shuō)明當(dāng)前線程沒(méi)有等待,而是直接開(kāi)啟了新線程,在新線程中執(zhí)行任務(wù)(異步執(zhí)行不做等待,可以繼續(xù)執(zhí)行任務(wù))。

接下來(lái)再來(lái)講講串行隊(duì)列的兩種執(zhí)行方式。

4.3 同步執(zhí)行 + 串行隊(duì)列

不會(huì)開(kāi)啟新線程,在當(dāng)前線程執(zhí)行任務(wù)。任務(wù)是串行的,執(zhí)行完一個(gè)任務(wù),再執(zhí)行下一個(gè)任務(wù)。

/**

* 同步執(zhí)行 + 串行隊(duì)列

* 特點(diǎn):不會(huì)開(kāi)啟新線程,在當(dāng)前線程執(zhí)行任務(wù)。任務(wù)是串行的,執(zhí)行完一個(gè)任務(wù),再執(zhí)行下一個(gè)任務(wù)。

*/- (void)syncSerial {NSLog(@"currentThread---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程N(yùn)SLog(@"syncSerial---begin");dispatch_queue_tqueue = dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_SERIAL);dispatch_sync(queue, ^{// 追加任務(wù)1for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"1---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });dispatch_sync(queue, ^{// 追加任務(wù)2for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"2---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });dispatch_sync(queue, ^{// 追加任務(wù)3for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"3---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });NSLog(@"syncSerial---end");}

輸出結(jié)果為:

2018-02-23 20:39:37.876811+0800 YSC-GCD-demo[19975:5017162] currentThread---{number = 1, name = main}

2018-02-23 20:39:37.876998+0800 YSC-GCD-demo[19975:5017162] syncSerial---begin

2018-02-23 20:39:39.878316+0800 YSC-GCD-demo[19975:5017162] 1---{number = 1, name = main}

2018-02-23 20:39:41.879829+0800 YSC-GCD-demo[19975:5017162] 1---{number = 1, name = main}

2018-02-23 20:39:43.880660+0800 YSC-GCD-demo[19975:5017162] 2---{number = 1, name = main}

2018-02-23 20:39:45.881265+0800 YSC-GCD-demo[19975:5017162] 2---{number = 1, name = main}

2018-02-23 20:39:47.882257+0800 YSC-GCD-demo[19975:5017162] 3---{number = 1, name = main}

2018-02-23 20:39:49.883008+0800 YSC-GCD-demo[19975:5017162] 3---{number = 1, name = main}

2018-02-23 20:39:49.883253+0800 YSC-GCD-demo[19975:5017162] syncSerial---end

在同步執(zhí)行 + 串行隊(duì)列可以看到:

所有任務(wù)都是在當(dāng)前線程(主線程)中執(zhí)行的,并沒(méi)有開(kāi)啟新的線程(同步執(zhí)行不具備開(kāi)啟新線程的能力)。

所有任務(wù)都在打印的syncConcurrent---begin和syncConcurrent---end之間執(zhí)行(同步任務(wù)需要等待隊(duì)列的任務(wù)執(zhí)行結(jié)束)。

任務(wù)是按順序執(zhí)行的(串行隊(duì)列每次只有一個(gè)任務(wù)被執(zhí)行,任務(wù)一個(gè)接一個(gè)按順序執(zhí)行)。

4.4 異步執(zhí)行 + 串行隊(duì)列

會(huì)開(kāi)啟新線程,但是因?yàn)槿蝿?wù)是串行的,執(zhí)行完一個(gè)任務(wù),再執(zhí)行下一個(gè)任務(wù)

/**

* 異步執(zhí)行 + 串行隊(duì)列

* 特點(diǎn):會(huì)開(kāi)啟新線程,但是因?yàn)槿蝿?wù)是串行的,執(zhí)行完一個(gè)任務(wù),再執(zhí)行下一個(gè)任務(wù)。

*/- (void)asyncSerial {NSLog(@"currentThread---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程N(yùn)SLog(@"asyncSerial---begin");dispatch_queue_tqueue = dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_SERIAL);dispatch_async(queue, ^{// 追加任務(wù)1for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"1---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });dispatch_async(queue, ^{// 追加任務(wù)2for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"2---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });dispatch_async(queue, ^{// 追加任務(wù)3for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"3---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });NSLog(@"asyncSerial---end");}

輸出結(jié)果為:

2018-02-23 20:41:17.029999+0800 YSC-GCD-demo[20008:5024757] currentThread---{number = 1, name = main}

2018-02-23 20:41:17.030212+0800 YSC-GCD-demo[20008:5024757] asyncSerial---begin

2018-02-23 20:41:17.030364+0800 YSC-GCD-demo[20008:5024757] asyncSerial---end

2018-02-23 20:41:19.035379+0800 YSC-GCD-demo[20008:5024950] 1---{number = 3, name = (null)}

2018-02-23 20:41:21.037140+0800 YSC-GCD-demo[20008:5024950] 1---{number = 3, name = (null)}

2018-02-23 20:41:23.042220+0800 YSC-GCD-demo[20008:5024950] 2---{number = 3, name = (null)}

2018-02-23 20:41:25.042971+0800 YSC-GCD-demo[20008:5024950] 2---{number = 3, name = (null)}

2018-02-23 20:41:27.047690+0800 YSC-GCD-demo[20008:5024950] 3---{number = 3, name = (null)}

2018-02-23 20:41:29.052327+0800 YSC-GCD-demo[20008:5024950] 3---{number = 3, name = (null)}

在異步執(zhí)行 + 串行隊(duì)列可以看到:

開(kāi)啟了一條新線程(異步執(zhí)行具備開(kāi)啟新線程的能力,串行隊(duì)列只開(kāi)啟一個(gè)線程)。

所有任務(wù)是在打印的syncConcurrent---begin和syncConcurrent---end之后才開(kāi)始執(zhí)行的(異步執(zhí)行不會(huì)做任何等待,可以繼續(xù)執(zhí)行任務(wù))。

任務(wù)是按順序執(zhí)行的(串行隊(duì)列每次只有一個(gè)任務(wù)被執(zhí)行,任務(wù)一個(gè)接一個(gè)按順序執(zhí)行)。

下邊講講剛才我們提到過(guò)的特殊隊(duì)列:主隊(duì)列。

主隊(duì)列:GCD自帶的一種特殊的串行隊(duì)列

所有放在主隊(duì)列中的任務(wù),都會(huì)放到主線程中執(zhí)行

可使用dispatch_get_main_queue()獲得主隊(duì)列

我們?cè)賮?lái)看看主隊(duì)列的兩種組合方式。

4.5 同步執(zhí)行 + 主隊(duì)列

同步執(zhí)行 + 主隊(duì)列在不同線程中調(diào)用結(jié)果也是不一樣,在主線程中調(diào)用會(huì)出現(xiàn)死鎖,而在其他線程中則不會(huì)。

4.5.1 在主線程中調(diào)用同步執(zhí)行 + 主隊(duì)列

互相等待卡住不可行

/**

* 同步執(zhí)行 + 主隊(duì)列

* 特點(diǎn)(主線程調(diào)用):互等卡主不執(zhí)行。

* 特點(diǎn)(其他線程調(diào)用):不會(huì)開(kāi)啟新線程,執(zhí)行完一個(gè)任務(wù),再執(zhí)行下一個(gè)任務(wù)。

*/- (void)syncMain {NSLog(@"currentThread---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程N(yùn)SLog(@"syncMain---begin");dispatch_queue_tqueue = dispatch_get_main_queue();dispatch_sync(queue, ^{// 追加任務(wù)1for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"1---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });dispatch_sync(queue, ^{// 追加任務(wù)2for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"2---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });dispatch_sync(queue, ^{// 追加任務(wù)3for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"3---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });NSLog(@"syncMain---end");}

輸出結(jié)果

2018-02-23 20:42:36.842892+0800 YSC-GCD-demo[20041:5030982] currentThread---{number = 1, name = main}

2018-02-23 20:42:36.843050+0800 YSC-GCD-demo[20041:5030982] syncMain---begin

(lldb)

在同步執(zhí)行 + 主隊(duì)列可以驚奇的發(fā)現(xiàn):

在主線程中使用同步執(zhí)行 + 主隊(duì)列,追加到主線程的任務(wù)1、任務(wù)2、任務(wù)3都不再執(zhí)行了,而且syncMain---end也沒(méi)有打印,在XCode 9上還會(huì)報(bào)崩潰。這是為什么呢?

這是因?yàn)槲覀冊(cè)谥骶€程中執(zhí)行syncMain方法,相當(dāng)于把syncMain任務(wù)放到了主線程的隊(duì)列中。而同步執(zhí)行會(huì)等待當(dāng)前隊(duì)列中的任務(wù)執(zhí)行完畢,才會(huì)接著執(zhí)行。那么當(dāng)我們把任務(wù)1追加到主隊(duì)列中,任務(wù)1就在等待主線程處理完syncMain任務(wù)。而syncMain任務(wù)需要等待任務(wù)1執(zhí)行完畢,才能接著執(zhí)行。

那么,現(xiàn)在的情況就是syncMain任務(wù)和任務(wù)1都在等對(duì)方執(zhí)行完畢。這樣大家互相等待,所以就卡住了,所以我們的任務(wù)執(zhí)行不了,而且syncMain---end也沒(méi)有打印。

要是如果不在主線程中調(diào)用,而在其他線程中調(diào)用會(huì)如何呢?

4.5.2 在其他線程中調(diào)用同步執(zhí)行 + 主隊(duì)列

不會(huì)開(kāi)啟新線程,執(zhí)行完一個(gè)任務(wù),再執(zhí)行下一個(gè)任務(wù)

// 使用 NSThread 的 detachNewThreadSelector 方法會(huì)創(chuàng)建線程,并自動(dòng)啟動(dòng)線程執(zhí)行selector 任務(wù)[NSThreaddetachNewThreadSelector:@selector(syncMain) toTarget:selfwithObject:nil];

輸出結(jié)果:

2018-02-23 20:44:19.377321+0800 YSC-GCD-demo[20083:5040347] currentThread---{number = 3, name = (null)}

2018-02-23 20:44:19.377494+0800 YSC-GCD-demo[20083:5040347] syncMain---begin

2018-02-23 20:44:21.384716+0800 YSC-GCD-demo[20083:5040132] 1---{number = 1, name = main}

2018-02-23 20:44:23.386091+0800 YSC-GCD-demo[20083:5040132] 1---{number = 1, name = main}

2018-02-23 20:44:25.387687+0800 YSC-GCD-demo[20083:5040132] 2---{number = 1, name = main}

2018-02-23 20:44:27.388648+0800 YSC-GCD-demo[20083:5040132] 2---{number = 1, name = main}

2018-02-23 20:44:29.390459+0800 YSC-GCD-demo[20083:5040132] 3---{number = 1, name = main}

2018-02-23 20:44:31.391965+0800 YSC-GCD-demo[20083:5040132] 3---{number = 1, name = main}

2018-02-23 20:44:31.392513+0800 YSC-GCD-demo[20083:5040347] syncMain---end

在其他線程中使用同步執(zhí)行 + 主隊(duì)列可看到:

所有任務(wù)都是在主線程(非當(dāng)前線程)中執(zhí)行的,沒(méi)有開(kāi)啟新的線程(所有放在主隊(duì)列中的任務(wù),都會(huì)放到主線程中執(zhí)行)。

所有任務(wù)都在打印的syncConcurrent---begin和syncConcurrent---end之間執(zhí)行(同步任務(wù)需要等待隊(duì)列的任務(wù)執(zhí)行結(jié)束)。

任務(wù)是按順序執(zhí)行的(主隊(duì)列是串行隊(duì)列,每次只有一個(gè)任務(wù)被執(zhí)行,任務(wù)一個(gè)接一個(gè)按順序執(zhí)行)。

為什么現(xiàn)在就不會(huì)卡住了呢?

因?yàn)閟yncMain 任務(wù)放到了其他線程里,而任務(wù)1、任務(wù)2、任務(wù)3都在追加到主隊(duì)列中,這三個(gè)任務(wù)都會(huì)在主線程中執(zhí)行。syncMain 任務(wù)在其他線程中執(zhí)行到追加任務(wù)1到主隊(duì)列中,因?yàn)橹麝?duì)列現(xiàn)在沒(méi)有正在執(zhí)行的任務(wù),所以,會(huì)直接執(zhí)行主隊(duì)列的任務(wù)1,等任務(wù)1執(zhí)行完畢,再接著執(zhí)行任務(wù)2、任務(wù)3。所以這里不會(huì)卡住線程。

4.6 異步執(zhí)行 + 主隊(duì)列

只在主線程中執(zhí)行任務(wù),執(zhí)行完一個(gè)任務(wù),再執(zhí)行下一個(gè)任務(wù)。

/**

* 異步執(zhí)行 + 主隊(duì)列

* 特點(diǎn):只在主線程中執(zhí)行任務(wù),執(zhí)行完一個(gè)任務(wù),再執(zhí)行下一個(gè)任務(wù)

*/- (void)asyncMain {NSLog(@"currentThread---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程N(yùn)SLog(@"asyncMain---begin");dispatch_queue_tqueue = dispatch_get_main_queue();dispatch_async(queue, ^{// 追加任務(wù)1for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"1---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });dispatch_async(queue, ^{// 追加任務(wù)2for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"2---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });dispatch_async(queue, ^{// 追加任務(wù)3for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"3---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });NSLog(@"asyncMain---end");}

輸出結(jié)果:

2018-02-23 20:45:49.981505+0800 YSC-GCD-demo[20111:5046708] currentThread---{number = 1, name = main}

2018-02-23 20:45:49.981935+0800 YSC-GCD-demo[20111:5046708] asyncMain---begin

2018-02-23 20:45:49.982352+0800 YSC-GCD-demo[20111:5046708] asyncMain---end

2018-02-23 20:45:51.991096+0800 YSC-GCD-demo[20111:5046708] 1---{number = 1, name = main}

2018-02-23 20:45:53.991959+0800 YSC-GCD-demo[20111:5046708] 1---{number = 1, name = main}

2018-02-23 20:45:55.992937+0800 YSC-GCD-demo[20111:5046708] 2---{number = 1, name = main}

2018-02-23 20:45:57.993649+0800 YSC-GCD-demo[20111:5046708] 2---{number = 1, name = main}

2018-02-23 20:45:59.994928+0800 YSC-GCD-demo[20111:5046708] 3---{number = 1, name = main}

2018-02-23 20:46:01.995589+0800 YSC-GCD-demo[20111:5046708] 3---{number = 1, name = main}

在異步執(zhí)行 + 主隊(duì)列可以看到:

所有任務(wù)都是在當(dāng)前線程(主線程)中執(zhí)行的,并沒(méi)有開(kāi)啟新的線程(雖然異步執(zhí)行具備開(kāi)啟線程的能力,但因?yàn)槭侵麝?duì)列,所以所有任務(wù)都在主線程中)。

所有任務(wù)是在打印的syncConcurrent---begin和syncConcurrent---end之后才開(kāi)始執(zhí)行的(異步執(zhí)行不會(huì)做任何等待,可以繼續(xù)執(zhí)行任務(wù))。

任務(wù)是按順序執(zhí)行的(因?yàn)橹麝?duì)列是串行隊(duì)列,每次只有一個(gè)任務(wù)被執(zhí)行,任務(wù)一個(gè)接一個(gè)按順序執(zhí)行)。

弄懂了難理解、繞來(lái)繞去的隊(duì)列+任務(wù)之后,我們來(lái)學(xué)習(xí)一個(gè)簡(jiǎn)單的東西:5. GCD 線程間的通信。

5. GCD 線程間的通信

在iOS開(kāi)發(fā)過(guò)程中,我們一般在主線程里邊進(jìn)行UI刷新,例如:點(diǎn)擊、滾動(dòng)、拖拽等事件。我們通常把一些耗時(shí)的操作放在其他線程,比如說(shuō)圖片下載、文件上傳等耗時(shí)操作。而當(dāng)我們有時(shí)候在其他線程完成了耗時(shí)操作時(shí),需要回到主線程,那么就用到了線程之間的通訊。

/**

* 線程間通信

*/- (void)communication {// 獲取全局并發(fā)隊(duì)列dispatch_queue_tqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);// 獲取主隊(duì)列dispatch_queue_tmainQueue = dispatch_get_main_queue();dispatch_async(queue, ^{// 異步追加任務(wù)for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"1---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}// 回到主線程dispatch_async(mainQueue, ^{// 追加在主線程中執(zhí)行的任務(wù)[NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"2---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程});? ? });}

輸出結(jié)果:

2018-02-23 20:47:03.462394+0800 YSC-GCD-demo[20154:5053282] 1---{number = 3, name = (null)}

2018-02-23 20:47:05.465912+0800 YSC-GCD-demo[20154:5053282] 1---{number = 3, name = (null)}

2018-02-23 20:47:07.466657+0800 YSC-GCD-demo[20154:5052953] 2---{number = 1, name = main}

可以看到在其他線程中先執(zhí)行任務(wù),執(zhí)行完了之后回到主線程執(zhí)行主線程的相應(yīng)操作。

6. GCD 的其他方法

6.1 GCD 柵欄方法:dispatch_barrier_async

我們有時(shí)需要異步執(zhí)行兩組操作,而且第一組操作執(zhí)行完之后,才能開(kāi)始執(zhí)行第二組操作。這樣我們就需要一個(gè)相當(dāng)于柵欄一樣的一個(gè)方法將兩組異步執(zhí)行的操作組給分割起來(lái),當(dāng)然這里的操作組里可以包含一個(gè)或多個(gè)任務(wù)。這就需要用到dispatch_barrier_async方法在兩個(gè)操作組間形成柵欄。

dispatch_barrier_async函數(shù)會(huì)等待前邊追加到并發(fā)隊(duì)列中的任務(wù)全部執(zhí)行完畢之后,再將指定的任務(wù)追加到該異步隊(duì)列中。然后在dispatch_barrier_async函數(shù)追加的任務(wù)執(zhí)行完畢之后,異步隊(duì)列才恢復(fù)為一般動(dòng)作,接著追加任務(wù)到該異步隊(duì)列并開(kāi)始執(zhí)行。具體如下圖所示:

dispatch_barrier_async.png

/**

* 柵欄方法 dispatch_barrier_async

*/- (void)barrier {dispatch_queue_tqueue = dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_CONCURRENT);dispatch_async(queue, ^{// 追加任務(wù)1for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"1---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });dispatch_async(queue, ^{// 追加任務(wù)2for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"2---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });? ? ? ? dispatch_barrier_async(queue, ^{// 追加任務(wù) barrierfor(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"barrier---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });dispatch_async(queue, ^{// 追加任務(wù)3for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"3---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });dispatch_async(queue, ^{// 追加任務(wù)4for(inti =0; i <2; ++i) {? ? ? ? ? ? [NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"4---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程}? ? });}

輸出結(jié)果:

2018-02-23 20:48:18.297745+0800 YSC-GCD-demo[20188:5059274] 1---{number = 4, name = (null)}

2018-02-23 20:48:18.297745+0800 YSC-GCD-demo[20188:5059273] 2---{number = 3, name = (null)}

2018-02-23 20:48:20.301139+0800 YSC-GCD-demo[20188:5059274] 1---{number = 4, name = (null)}

2018-02-23 20:48:20.301139+0800 YSC-GCD-demo[20188:5059273] 2---{number = 3, name = (null)}

2018-02-23 20:48:22.306290+0800 YSC-GCD-demo[20188:5059274] barrier---{number = 4, name = (null)}

2018-02-23 20:48:24.311655+0800 YSC-GCD-demo[20188:5059274] barrier---{number = 4, name = (null)}

2018-02-23 20:48:26.316943+0800 YSC-GCD-demo[20188:5059273] 4---{number = 3, name = (null)}

2018-02-23 20:48:26.316956+0800 YSC-GCD-demo[20188:5059274] 3---{number = 4, name = (null)}

2018-02-23 20:48:28.320660+0800 YSC-GCD-demo[20188:5059273] 4---{number = 3, name = (null)}

2018-02-23 20:48:28.320649+0800 YSC-GCD-demo[20188:5059274] 3---{number = 4, name = (null)}

在dispatch_barrier_async執(zhí)行結(jié)果中可以看出:

在執(zhí)行完?yáng)艡谇懊娴牟僮髦?,才?zhí)行柵欄操作,最后再執(zhí)行柵欄后邊的操作。

6.2 GCD 延時(shí)執(zhí)行方法:dispatch_after

我們經(jīng)常會(huì)遇到這樣的需求:在指定時(shí)間(例如3秒)之后執(zhí)行某個(gè)任務(wù)??梢杂?GCD 的dispatch_after函數(shù)來(lái)實(shí)現(xiàn)。

需要注意的是:dispatch_after函數(shù)并不是在指定時(shí)間之后才開(kāi)始執(zhí)行處理,而是在指定時(shí)間之后將任務(wù)追加到主隊(duì)列中。嚴(yán)格來(lái)說(shuō),這個(gè)時(shí)間并不是絕對(duì)準(zhǔn)確的,但想要大致延遲執(zhí)行任務(wù),dispatch_after函數(shù)是很有效的。

/**

* 延時(shí)執(zhí)行方法 dispatch_after

*/- (void)after {NSLog(@"currentThread---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程N(yùn)SLog(@"asyncMain---begin");? ? ? ? dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{// 2.0秒后異步追加任務(wù)代碼到主隊(duì)列,并開(kāi)始執(zhí)行NSLog(@"after---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程});}

輸出結(jié)果:

2018-02-23 20:53:08.713784+0800 YSC-GCD-demo[20282:5080295] currentThread---{number = 1, name = main}

2018-02-23 20:53:08.713962+0800 YSC-GCD-demo[20282:5080295] asyncMain---begin

2018-02-23 20:53:10.714283+0800 YSC-GCD-demo[20282:5080295] after---{number = 1, name = main}

可以看出:在打印asyncMain---begin之后大約 2.0 秒的時(shí)間,打印了after---<NSThread: 0x60000006ee00>{number = 1, name = main}

6.3 GCD 一次性代碼(只執(zhí)行一次):dispatch_once

我們?cè)趧?chuàng)建單例、或者有整個(gè)程序運(yùn)行過(guò)程中只執(zhí)行一次的代碼時(shí),我們就用到了 GCD 的dispatch_once函數(shù)。使用

dispatch_once函數(shù)能保證某段代碼在程序運(yùn)行過(guò)程中只被執(zhí)行1次,并且即使在多線程的環(huán)境下,dispatch_once也可以保證線程安全。

/**

* 一次性代碼(只執(zhí)行一次)dispatch_once

*/- (void)once {staticdispatch_once_tonceToken;dispatch_once(&onceToken, ^{// 只執(zhí)行1次的代碼(這里面默認(rèn)是線程安全的)});}

6.4 GCD 快速迭代方法:dispatch_apply

通常我們會(huì)用 for 循環(huán)遍歷,但是 GCD 給我們提供了快速迭代的函數(shù)dispatch_apply。dispatch_apply按照指定的次數(shù)將指定的任務(wù)追加到指定的隊(duì)列中,并等待全部隊(duì)列執(zhí)行結(jié)束。

如果是在串行隊(duì)列中使用dispatch_apply,那么就和 for 循環(huán)一樣,按順序同步執(zhí)行??蛇@樣就體現(xiàn)不出快速迭代的意義了。

我們可以利用并發(fā)隊(duì)列進(jìn)行異步執(zhí)行。比如說(shuō)遍歷 0~5 這6個(gè)數(shù)字,for 循環(huán)的做法是每次取出一個(gè)元素,逐個(gè)遍歷。dispatch_apply可以 在多個(gè)線程中同時(shí)(異步)遍歷多個(gè)數(shù)字。

還有一點(diǎn),無(wú)論是在串行隊(duì)列,還是異步隊(duì)列中,dispatch_apply 都會(huì)等待全部任務(wù)執(zhí)行完畢,這點(diǎn)就像是同步操作,也像是隊(duì)列組中的dispatch_group_wait方法。

/**

* 快速迭代方法 dispatch_apply

*/- (void)apply {dispatch_queue_tqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);NSLog(@"apply---begin");? ? dispatch_apply(6, queue, ^(size_t index) {NSLog(@"%zd---%@",index, [NSThreadcurrentThread]);? ? });NSLog(@"apply---end");}

輸出結(jié)果:

2018-02-23 22:03:18.475499+0800 YSC-GCD-demo[20470:5176805] apply---begin

2018-02-23 22:03:18.476672+0800 YSC-GCD-demo[20470:5177035] 1---{number = 3, name = (null)}

2018-02-23 22:03:18.476693+0800 YSC-GCD-demo[20470:5176805] 0---{number = 1, name = main}

2018-02-23 22:03:18.476704+0800 YSC-GCD-demo[20470:5177037] 2---{number = 4, name = (null)}

2018-02-23 22:03:18.476735+0800 YSC-GCD-demo[20470:5177036] 3---{number = 5, name = (null)}

2018-02-23 22:03:18.476867+0800 YSC-GCD-demo[20470:5177035] 4---{number = 3, name = (null)}

2018-02-23 22:03:18.476867+0800 YSC-GCD-demo[20470:5176805] 5---{number = 1, name = main}

2018-02-23 22:03:18.477038+0800 YSC-GCD-demo[20470:5176805] apply---end

因?yàn)槭窃诓l(fā)隊(duì)列中異步執(zhí)行任務(wù),所以各個(gè)任務(wù)的執(zhí)行時(shí)間長(zhǎng)短不定,最后結(jié)束順序也不定。但是apply---end一定在最后執(zhí)行。這是因?yàn)閐ispatch_apply函數(shù)會(huì)等待全部任務(wù)執(zhí)行完畢。

6.5 GCD 隊(duì)列組:dispatch_group

有時(shí)候我們會(huì)有這樣的需求:分別異步執(zhí)行2個(gè)耗時(shí)任務(wù),然后當(dāng)2個(gè)耗時(shí)任務(wù)都執(zhí)行完畢后再回到主線程執(zhí)行任務(wù)。這時(shí)候我們可以用到 GCD 的隊(duì)列組。

調(diào)用隊(duì)列組的dispatch_group_async先把任務(wù)放到隊(duì)列中,然后將隊(duì)列放入隊(duì)列組中。或者使用隊(duì)列組的dispatch_group_enter、dispatch_group_leave組合 來(lái)實(shí)現(xiàn)

dispatch_group_async。

調(diào)用隊(duì)列組的dispatch_group_notify回到指定線程執(zhí)行任務(wù)?;蛘呤褂胐ispatch_group_wait回到當(dāng)前線程繼續(xù)向下執(zhí)行(會(huì)阻塞當(dāng)前線程)。

6.5.1 dispatch_group_notify

監(jiān)聽(tīng) group 中任務(wù)的完成狀態(tài),當(dāng)所有的任務(wù)都執(zhí)行完成后,追加任務(wù)到 group 中,并執(zhí)行任務(wù)。


* 隊(duì)列組 dispatch_group_notify

6.5.2 dispatch_group_wait

暫停當(dāng)前線程(阻塞當(dāng)前線程),等待指定的 group 中的任務(wù)執(zhí)行完成后,才會(huì)往下繼續(xù)執(zhí)行。

/**

* 隊(duì)列組 dispatch_group_wait

當(dāng) group 中未執(zhí)行完畢任務(wù)數(shù)為0的時(shí)候,才會(huì)使dispatch_group_wait解除阻塞,以及執(zhí)行追加到dispatch_group_notify中的任務(wù)。

/**

* 隊(duì)列組 dispatch_group_enter、dispatch_group_leave


從dispatch_group_enter、dispatch_group_leave相關(guān)代碼運(yùn)行結(jié)果中可以看出:當(dāng)所有任務(wù)執(zhí)行完成之后,才執(zhí)行 dispatch_group_notify 中的任務(wù)。這里的dispatch_group_enter、dispatch_group_leave組合,其實(shí)等同于dispatch_group_async。

6.6 GCD 信號(hào)量:dispatch_semaphore

GCD 中的信號(hào)量是指Dispatch Semaphore,是持有計(jì)數(shù)的信號(hào)。類似于過(guò)高速路收費(fèi)站的欄桿。可以通過(guò)時(shí),打開(kāi)欄桿,不可以通過(guò)時(shí),關(guān)閉欄桿。在Dispatch Semaphore中,使用計(jì)數(shù)來(lái)完成這個(gè)功能,計(jì)數(shù)為0時(shí)等待,不可通過(guò)。計(jì)數(shù)為1或大于1時(shí),計(jì)數(shù)減1且不等待,可通過(guò)。

Dispatch Semaphore提供了三個(gè)函數(shù)。

dispatch_semaphore_create:創(chuàng)建一個(gè)Semaphore并初始化信號(hào)的總量

dispatch_semaphore_signal:發(fā)送一個(gè)信號(hào),讓信號(hào)總量加1

dispatch_semaphore_wait:可以使總信號(hào)量減1,當(dāng)信號(hào)總量為0時(shí)就會(huì)一直等待(阻塞所在線程),否則就可以正常執(zhí)行。

注意:信號(hào)量的使用前提是:想清楚你需要處理哪個(gè)線程等待(阻塞),又要哪個(gè)線程繼續(xù)執(zhí)行,然后使用信號(hào)量。

Dispatch Semaphore 在實(shí)際開(kāi)發(fā)中主要用于:

保持線程同步,將異步執(zhí)行任務(wù)轉(zhuǎn)換為同步執(zhí)行任務(wù)

保證線程安全,為線程加鎖

6.6.1 Dispatch Semaphore 線程同步

我們?cè)陂_(kāi)發(fā)中,會(huì)遇到這樣的需求:異步執(zhí)行耗時(shí)任務(wù),并使用異步執(zhí)行的結(jié)果進(jìn)行一些額外的操作。換句話說(shuō),相當(dāng)于,將將異步執(zhí)行任務(wù)轉(zhuǎn)換為同步執(zhí)行任務(wù)。比如說(shuō):AFNetworking 中 AFURLSessionManager.m 里面的tasksForKeyPath:方法。通過(guò)引入信號(hào)量的方式,等待異步執(zhí)行任務(wù)結(jié)果,獲取到 tasks,然后再返回該 tasks。

- (NSArray*)tasksForKeyPath:(NSString*)keyPath {? ? __blockNSArray*tasks =nil;? ? dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);? ? [self.session getTasksWithCompletionHandler:^(NSArray*dataTasks,NSArray*uploadTasks,NSArray*downloadTasks) {if([keyPath isEqualToString:NSStringFromSelector(@selector(dataTasks))]) {? ? ? ? ? ? tasks = dataTasks;? ? ? ? }elseif([keyPath isEqualToString:NSStringFromSelector(@selector(uploadTasks))]) {? ? ? ? ? ? tasks = uploadTasks;? ? ? ? }elseif([keyPath isEqualToString:NSStringFromSelector(@selector(downloadTasks))]) {? ? ? ? ? ? tasks = downloadTasks;? ? ? ? }elseif([keyPath isEqualToString:NSStringFromSelector(@selector(tasks))]) {? ? ? ? ? ? tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"];? ? ? ? }? ? ? ? dispatch_semaphore_signal(semaphore);? ? }];? ? dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);returntasks;}

下面,我們來(lái)利用 Dispatch Semaphore 實(shí)現(xiàn)線程同步,將異步執(zhí)行任務(wù)轉(zhuǎn)換為同步執(zhí)行任務(wù)。

/**

* semaphore 線程同步

*/- (void)semaphoreSync {NSLog(@"currentThread---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程N(yùn)SLog(@"semaphore---begin");dispatch_queue_tqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);? ? dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);? ? ? ? __blockintnumber =0;dispatch_async(queue, ^{// 追加任務(wù)1[NSThreadsleepForTimeInterval:2];// 模擬耗時(shí)操作NSLog(@"1---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程number =100;? ? ? ? ? ? ? ? dispatch_semaphore_signal(semaphore);? ? });? ? ? ? dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);NSLog(@"semaphore---end,number = %zd",number);}

輸出結(jié)果:

2018-02-23 22:22:26.521665+0800 YSC-GCD-demo[20642:5246341] currentThread---{number = 1, name = main}

2018-02-23 22:22:26.521869+0800 YSC-GCD-demo[20642:5246341] semaphore---begin

2018-02-23 22:22:28.526841+0800 YSC-GCD-demo[20642:5246638] 1---{number = 3, name = (null)}

2018-02-23 22:22:28.527030+0800 YSC-GCD-demo[20642:5246341] semaphore---end,number = 100

從 Dispatch Semaphore 實(shí)現(xiàn)線程同步的代碼可以看到:

semaphore---end是在執(zhí)行完number = 100;之后才打印的。而且輸出結(jié)果 number 為 100。

這是因?yàn)楫惒綀?zhí)行不會(huì)做任何等待,可以繼續(xù)執(zhí)行任務(wù)。異步執(zhí)行將任務(wù)1追加到隊(duì)列之后,不做等待,接著執(zhí)行dispatch_semaphore_wait方法。此時(shí) semaphore == 0,當(dāng)前線程進(jìn)入等待狀態(tài)。然后,異步任務(wù)1開(kāi)始執(zhí)行。任務(wù)1執(zhí)行到dispatch_semaphore_signal之后,總信號(hào)量,此時(shí) semaphore == 1,dispatch_semaphore_wait方法使總信號(hào)量減1,正在被阻塞的線程(主線程)恢復(fù)繼續(xù)執(zhí)行。最后打印semaphore---end,number = 100。這樣就實(shí)現(xiàn)了線程同步,將異步執(zhí)行任務(wù)轉(zhuǎn)換為同步執(zhí)行任務(wù)。

6.6.2 Dispatch Semaphore 線程安全和線程同步(為線程加鎖)

線程安全:如果你的代碼所在的進(jìn)程中有多個(gè)線程在同時(shí)運(yùn)行,而這些線程可能會(huì)同時(shí)運(yùn)行這段代碼。如果每次運(yùn)行結(jié)果和單線程運(yùn)行的結(jié)果是一樣的,而且其他的變量的值也和預(yù)期的是一樣的,就是線程安全的。

若每個(gè)線程中對(duì)全局變量、靜態(tài)變量只有讀操作,而無(wú)寫(xiě)操作,一般來(lái)說(shuō),這個(gè)全局變量是線程安全的;若有多個(gè)線程同時(shí)執(zhí)行寫(xiě)操作(更改變量),一般都需要考慮線程同步,否則的話就可能影響線程安全。

線程同步:可理解為線程 A 和 線程 B 一塊配合,A 執(zhí)行到一定程度時(shí)要依靠線程 B 的某個(gè)結(jié)果,于是停下來(lái),示意 B 運(yùn)行;B 依言執(zhí)行,再將結(jié)果給 A;A 再繼續(xù)操作。

舉個(gè)簡(jiǎn)單例子就是:兩個(gè)人在一起聊天。兩個(gè)人不能同時(shí)說(shuō)話,避免聽(tīng)不清(操作沖突)。等一個(gè)人說(shuō)完(一個(gè)線程結(jié)束操作),另一個(gè)再說(shuō)(另一個(gè)線程再開(kāi)始操作)。

下面,我們模擬火車票售賣的方式,實(shí)現(xiàn) NSThread 線程安全和解決線程同步問(wèn)題。

場(chǎng)景:總共有50張火車票,有兩個(gè)售賣火車票的窗口,一個(gè)是北京火車票售賣窗口,另一個(gè)是上?;疖嚻笔圪u窗口。兩個(gè)窗口同時(shí)售賣火車票,賣完為止。

6.6.2.1 非線程安全(不使用 semaphore)

先來(lái)看看不考慮線程安全的代碼:

/**

* 非線程安全:不使用 semaphore

* 初始化火車票數(shù)量、賣票窗口(非線程安全)、并開(kāi)始賣票

*/- (void)initTicketStatusNotSave {NSLog(@"currentThread---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程N(yùn)SLog(@"semaphore---begin");self.ticketSurplusCount =50;// queue1 代表北京火車票售賣窗口dispatch_queue_tqueue1 = dispatch_queue_create("net.bujige.testQueue1", DISPATCH_QUEUE_SERIAL);// queue2 代表上?;疖嚻笔圪u窗口dispatch_queue_tqueue2 = dispatch_queue_create("net.bujige.testQueue2", DISPATCH_QUEUE_SERIAL);? ? ? ? __weaktypeof(self) weakSelf =self;dispatch_async(queue1, ^{? ? ? ? [weakSelf saleTicketNotSafe];? ? });dispatch_async(queue2, ^{? ? ? ? [weakSelf saleTicketNotSafe];? ? });}/**

* 售賣火車票(非線程安全)

*/- (void)saleTicketNotSafe {while(1) {if(self.ticketSurplusCount >0) {//如果還有票,繼續(xù)售賣self.ticketSurplusCount--;NSLog(@"%@", [NSStringstringWithFormat:@"剩余票數(shù):%d 窗口:%@",self.ticketSurplusCount, [NSThreadcurrentThread]]);? ? ? ? ? ? [NSThreadsleepForTimeInterval:0.2];? ? ? ? }else{//如果已賣完,關(guān)閉售票窗口NSLog(@"所有火車票均已售完");break;? ? ? ? }? ? ? ? ? ? }}

輸出結(jié)果(部分):

2018-02-23 22:25:35.789072+0800 YSC-GCD-demo[20712:5258914] currentThread---{number = 1, name = main}

2018-02-23 22:25:35.789260+0800 YSC-GCD-demo[20712:5258914] semaphore---begin

2018-02-23 22:25:35.789641+0800 YSC-GCD-demo[20712:5259176] 剩余票數(shù):48 窗口:{number = 3, name = (null)}

2018-02-23 22:25:35.789646+0800 YSC-GCD-demo[20712:5259175] 剩余票數(shù):49 窗口:{number = 4, name = (null)}

2018-02-23 22:25:35.994113+0800 YSC-GCD-demo[20712:5259175] 剩余票數(shù):47 窗口:{number = 4, name = (null)}

2018-02-23 22:25:35.994129+0800 YSC-GCD-demo[20712:5259176] 剩余票數(shù):46 窗口:{number = 3, name = (null)}

2018-02-23 22:25:36.198993+0800 YSC-GCD-demo[20712:5259176] 剩余票數(shù):45 窗口:{number = 3, name = (null)}

...

可以看到在不考慮線程安全,不使用 semaphore 的情況下,得到票數(shù)是錯(cuò)亂的,這樣顯然不符合我們的需求,所以我們需要考慮線程安全問(wèn)題。

6.6.2.2 線程安全(使用 semaphore 加鎖)

考慮線程安全的代碼:

/**

* 線程安全:使用 semaphore 加鎖

* 初始化火車票數(shù)量、賣票窗口(線程安全)、并開(kāi)始賣票

*/- (void)initTicketStatusSave {NSLog(@"currentThread---%@",[NSThreadcurrentThread]);// 打印當(dāng)前線程N(yùn)SLog(@"semaphore---begin");? ? ? ? semaphoreLock = dispatch_semaphore_create(1);self.ticketSurplusCount =50;// queue1 代表北京火車票售賣窗口dispatch_queue_tqueue1 = dispatch_queue_create("net.bujige.testQueue1", DISPATCH_QUEUE_SERIAL);// queue2 代表上?;疖嚻笔圪u窗口dispatch_queue_tqueue2 = dispatch_queue_create("net.bujige.testQueue2", DISPATCH_QUEUE_SERIAL);? ? ? ? __weaktypeof(self) weakSelf =self;dispatch_async(queue1, ^{? ? ? ? [weakSelf saleTicketSafe];? ? });dispatch_async(queue2, ^{? ? ? ? [weakSelf saleTicketSafe];? ? });}/**

* 售賣火車票(線程安全)

*/- (void)saleTicketSafe {while(1) {// 相當(dāng)于加鎖dispatch_semaphore_wait(semaphoreLock, DISPATCH_TIME_FOREVER);if(self.ticketSurplusCount >0) {//如果還有票,繼續(xù)售賣self.ticketSurplusCount--;NSLog(@"%@", [NSStringstringWithFormat:@"剩余票數(shù):%d 窗口:%@",self.ticketSurplusCount, [NSThreadcurrentThread]]);? ? ? ? ? ? [NSThreadsleepForTimeInterval:0.2];? ? ? ? }else{//如果已賣完,關(guān)閉售票窗口NSLog(@"所有火車票均已售完");// 相當(dāng)于解鎖dispatch_semaphore_signal(semaphoreLock);break;? ? ? ? }// 相當(dāng)于解鎖dispatch_semaphore_signal(semaphoreLock);? ? }}

輸出結(jié)果為:

2018-02-23 22:32:19.814232+0800 YSC-GCD-demo[20862:5290531] currentThread---{number = 1, name = main}

2018-02-23 22:32:19.814412+0800 YSC-GCD-demo[20862:5290531] semaphore---begin

2018-02-23 22:32:19.814837+0800 YSC-GCD-demo[20862:5290687] 剩余票數(shù):49 窗口:{number = 3, name = (null)}

2018-02-23 22:32:20.017745+0800 YSC-GCD-demo[20862:5290689] 剩余票數(shù):48 窗口:{number = 4, name = (null)}

2018-02-23 22:32:20.222039+0800 YSC-GCD-demo[20862:5290687] 剩余票數(shù):47 窗口:{number = 3, name = (null)}

...

2018-02-23 22:32:29.024817+0800 YSC-GCD-demo[20862:5290689] 剩余票數(shù):4 窗口:{number = 4, name = (null)}

2018-02-23 22:32:29.230110+0800 YSC-GCD-demo[20862:5290687] 剩余票數(shù):3 窗口:{number = 3, name = (null)}

2018-02-23 22:32:29.433615+0800 YSC-GCD-demo[20862:5290689] 剩余票數(shù):2 窗口:{number = 4, name = (null)}

2018-02-23 22:32:29.637572+0800 YSC-GCD-demo[20862:5290687] 剩余票數(shù):1 窗口:{number = 3, name = (null)}

2018-02-23 22:32:29.840234+0800 YSC-GCD-demo[20862:5290689] 剩余票數(shù):0 窗口:{number = 4, name = (null)}

2018-02-23 22:32:30.044960+0800 YSC-GCD-demo[20862:5290687] 所有火車票均已售完

2018-02-23 22:32:30.045260+0800 YSC-GCD-demo[20862:5290689] 所有火車票均已售完

可以看出,在考慮了線程安全的情況下,使用dispatch_semaphore

機(jī)制之后,得到的票數(shù)是正確的,沒(méi)有出現(xiàn)混亂的情況。我們也就解決了多個(gè)線程同步的問(wèn)題。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)...
    七魂之月閱讀 905評(píng)論 1 16
  • 測(cè)試現(xiàn)在被普遍認(rèn)為“保證產(chǎn)品質(zhì)量”這個(gè)籠統(tǒng)的說(shuō)法下,而測(cè)試本身是什么呢?今天我們就測(cè)試本身跟大家一起討論。 測(cè)試是...
    西邊人閱讀 4,696評(píng)論 2 52
  • 文章來(lái)自:http://blog.csdn.net/mj813/article/details/52451355 ...
    好大一只鵬閱讀 9,214評(píng)論 2 126
  • 1****、問(wèn):你在測(cè)試中發(fā)現(xiàn)了一個(gè)bug****,但是開(kāi)發(fā)經(jīng)理認(rèn)為這不是一個(gè)bug****,你應(yīng)該怎樣解決? 首...
    蛋炒飯_By閱讀 5,306評(píng)論 1 94
  • 1.測(cè)試與軟件模型 軟件開(kāi)發(fā)生命周期模型指的是軟件開(kāi)發(fā)全過(guò)程、活動(dòng)和任務(wù)的結(jié)構(gòu)性框架。軟件項(xiàng)目的開(kāi)發(fā)包括:需求、設(shè)...
    宇文臭臭閱讀 6,745評(píng)論 5 100