多線程之1-GCD(DispatchQueue)

GCD的特點(diǎn)

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

GCD自動(dòng)管理線程的生命周期(創(chuàng)建線程磕洪,調(diào)度任務(wù),銷毀線程等)

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

1.GCD 相關(guān)概念

任務(wù)(block):就是需要執(zhí)行的代碼塊析显,以block 的方式呈現(xiàn)。
同步(sync): 在當(dāng)前線程中執(zhí)行签赃,會(huì)阻塞當(dāng)前線程谷异,不會(huì)開啟新的線程,所以只能一次執(zhí)行一個(gè)任務(wù)锦聊,前一個(gè)任務(wù)執(zhí)行完畢歹嘹,當(dāng)前線程才會(huì)執(zhí)行后一個(gè)任務(wù)
異步(async):不阻塞當(dāng)前線程,由GCD 決定是否開啟新的線程
隊(duì)列(queue):裝載待執(zhí)行任務(wù)的一種隊(duì)形結(jié)構(gòu)孔庭,和排隊(duì)上車一樣尺上,先進(jìn)先出。GCD 中有兩種隊(duì)列結(jié)構(gòu):串行隊(duì)列和并發(fā)隊(duì)列圆到。
串行隊(duì)列(serialQueue):隊(duì)列中的任務(wù)只能按順序依次執(zhí)行怎抛。
并發(fā)隊(duì)列(conCurrentQueue):隊(duì)列中的任務(wù)可以多個(gè)同時(shí)執(zhí)行,在async 下是真正的并發(fā)构资,在sync 下依然是串行,因?yàn)橹挥幸粭l線程可用陨簇。
GCD是將要執(zhí)行的代碼加入隊(duì)列中(串行隊(duì)列或并發(fā)隊(duì)列)吐绵,然后指定運(yùn)行方式(同步執(zhí)行或異步執(zhí)行)

2.創(chuàng)建隊(duì)列

GCD 需要把代碼塊放到隊(duì)列中,隊(duì)列又分串行隊(duì)列和并發(fā)隊(duì)列河绽。
第一個(gè)參數(shù) label 是隊(duì)列的標(biāo)識(shí)符己单,可以為空,第二個(gè)attributes 是表示串行或者并發(fā)隊(duì)列耙饰。默認(rèn)為串行隊(duì)列纹笼,.concurren 表示并發(fā)隊(duì)列。

// 串行隊(duì)列
 let serialQueue = DispatchQueue(label: "dispatchSeralQueue")
//并發(fā)隊(duì)列
 let conCurrentQueue = DispatchQueue(label: "dispatchConcurrentQueue", attributes: .concurrent)

除了自定義的隊(duì)列苟跪,系統(tǒng)還我們提供了兩個(gè)隊(duì)列
主隊(duì)列廷痘,主隊(duì)列是一個(gè)并發(fā)隊(duì)列。

DispatchQueue.main.async {
            
}

全局隊(duì)列件已,是一個(gè)并發(fā)隊(duì)列

 DispatchQueue.global().async {
            
 }

3.GCD使用

隊(duì)列和同步異步之間有多種組合方式
1.串行同步
2.串行異步
3.并發(fā)同步
4.并發(fā)異步
5.主隊(duì)列同步
6.主隊(duì)列異步

  • 串行同步
let seralQueue = DispatchQueue(label: "dispatchSeralQueue")
        seralQueue.sync {
            for i in 0...3 {
                debugPrint("queueTest seralQueue1: \(Thread.current), \(i)")
            }
        }
        seralQueue.sync {
            for i in 0...3 {
                debugPrint("queueTest seralQueue2: \(Thread.current), \(i)")
            }
        }
"queueTest seralQueue1: <_NSMainThread: 0x600003db08c0>{number = 1, name = main}, 0"
"queueTest seralQueue1: <_NSMainThread: 0x600003db08c0>{number = 1, name = main}, 1"
"queueTest seralQueue1: <_NSMainThread: 0x600003db08c0>{number = 1, name = main}, 2"
"queueTest seralQueue1: <_NSMainThread: 0x600003db08c0>{number = 1, name = main}, 3"
"queueTest seralQueue2: <_NSMainThread: 0x600003db08c0>{number = 1, name = main}, 0"
"queueTest seralQueue2: <_NSMainThread: 0x600003db08c0>{number = 1, name = main}, 1"
"queueTest seralQueue2: <_NSMainThread: 0x600003db08c0>{number = 1, name = main}, 2"
"queueTest seralQueue2: <_NSMainThread: 0x600003db08c0>{number = 1, name = main}, 3"

結(jié)果笋额,順序執(zhí)行,都在主線程

  • 串行異步
let seralQueue = DispatchQueue(label: "dispatchSeralQueue")
        seralQueue.async {
            for i in 0...3 {
                debugPrint("queueTest seralQueue1: \(Thread.current), \(i)")
            }
        }
        seralQueue.async {
            for i in 0...3 {
                debugPrint("queueTest seralQueue2: \(Thread.current), \(i)")
            }
        }
"queueTest seralQueue1: <NSThread: 0x6000030d2c40>{number = 6, name = (null)}, 0"
"queueTest seralQueue1: <NSThread: 0x6000030d2c40>{number = 6, name = (null)}, 1"
"queueTest seralQueue1: <NSThread: 0x6000030d2c40>{number = 6, name = (null)}, 2"
"queueTest seralQueue1: <NSThread: 0x6000030d2c40>{number = 6, name = (null)}, 3"
"queueTest seralQueue2: <NSThread: 0x6000030d2c40>{number = 6, name = (null)}, 0"
"queueTest seralQueue2: <NSThread: 0x6000030d2c40>{number = 6, name = (null)}, 1"
"queueTest seralQueue2: <NSThread: 0x6000030d2c40>{number = 6, name = (null)}, 2"
"queueTest seralQueue2: <NSThread: 0x6000030d2c40>{number = 6, name = (null)}, 3"

結(jié)果不在主線程篷扩,但是依然是順序執(zhí)行

  • 并發(fā)同步
let conCurrentQueue = DispatchQueue(label: "dispatchConcurrentQueue", attributes: .concurrent)
        conCurrentQueue.sync {
            for i in 0...3 {
                debugPrint("queueTest conCurrentQueue1: \(Thread.current), \(i)")
            }
        }
        conCurrentQueue.sync {
            for i in 0...3 {
                debugPrint("queueTest conCurrentQueue2: \(Thread.current), \(i)")
            }
        }
"queueTest conCurrentQueue1: <_NSMainThread: 0x600000648380>{number = 1, name = main}, 0"
"queueTest conCurrentQueue1: <_NSMainThread: 0x600000648380>{number = 1, name = main}, 1"
"queueTest conCurrentQueue1: <_NSMainThread: 0x600000648380>{number = 1, name = main}, 2"
"queueTest conCurrentQueue1: <_NSMainThread: 0x600000648380>{number = 1, name = main}, 3"
"queueTest conCurrentQueue2: <_NSMainThread: 0x600000648380>{number = 1, name = main}, 0"
"queueTest conCurrentQueue2: <_NSMainThread: 0x600000648380>{number = 1, name = main}, 1"
"queueTest conCurrentQueue2: <_NSMainThread: 0x600000648380>{number = 1, name = main}, 2"
"queueTest conCurrentQueue2: <_NSMainThread: 0x600000648380>{number = 1, name = main}, 3"

在主線程兄猩,順序執(zhí)行

  • 并發(fā)異步
let conCurrentQueue = DispatchQueue(label: "dispatchConcurrentQueue", attributes: .concurrent)
        conCurrentQueue.async {
            for i in 0...3 {
                debugPrint("queueTest conCurrentQueue1: \(Thread.current), \(i)")
            }
        }
        conCurrentQueue.async {
            for i in 0...3 {
                debugPrint("queueTest conCurrentQueue2: \(Thread.current), \(i)")
            }
        }
"queueTest conCurrentQueue2: <NSThread: 0x600003bf2900>{number = 4, name = (null)}, 0"
"queueTest conCurrentQueue1: <NSThread: 0x600003b98240>{number = 6, name = (null)}, 0"
"queueTest conCurrentQueue2: <NSThread: 0x600003bf2900>{number = 4, name = (null)}, 1"
"queueTest conCurrentQueue1: <NSThread: 0x600003b98240>{number = 6, name = (null)}, 1"
"queueTest conCurrentQueue2: <NSThread: 0x600003bf2900>{number = 4, name = (null)}, 2"
"queueTest conCurrentQueue1: <NSThread: 0x600003b98240>{number = 6, name = (null)}, 2"
"queueTest conCurrentQueue2: <NSThread: 0x600003bf2900>{number = 4, name = (null)}, 3"
"queueTest conCurrentQueue1: <NSThread: 0x600003b98240>{number = 6, name = (null)}, 3"

任務(wù)同時(shí)進(jìn)行,開啟多個(gè)線程。

 DispatchQueue.global().async {
            // 模擬耗時(shí)操作
            Thread.sleep(forTimeInterval: 10)
            DispatchQueue.main.async {
                // 在主隊(duì)列插入一個(gè)任務(wù)更新UI
            }
        }

-GCD 柵欄函數(shù)
當(dāng)任務(wù)需要異步進(jìn)行,但是這些任務(wù)需要分成兩組來執(zhí)行淹真,第一組完成之后才能進(jìn)行第二組的操作讶迁。這時(shí)候就用了到GCD的柵欄方法:

let dispathGroup = DispatchGroup()
        let dispatchConcurrentQueue = DispatchQueue(label: "dispatchConcurrentQueue", attributes: .concurrent)
        dispatchConcurrentQueue.async {
            for i in 0...3 {
                debugPrint("dispatchConcurrentQueue action1 \(i) at \(Thread.current)")
            }
            
        }
        dispatchConcurrentQueue.async {
            for i in 0...3 {
                debugPrint("dispatchConcurrentQueue action2 \(i) at \(Thread.current)")
            }
            
        }
        dispatchConcurrentQueue.async(group: dispathGroup, qos: .default, flags: .barrier) {
            debugPrint("dispatchConcurrentQueue barrier")
        }
        dispatchConcurrentQueue.async {
            for i in 0...3 {
                debugPrint("dispatchConcurrentQueue action3 \(i) at \(Thread.current)")
            }
            
        }
        dispatchConcurrentQueue.async {
            for i in 0...3 {
                debugPrint("dispatchConcurrentQueue action4 \(i) at \(Thread.current)")
            }
            
        }
"dispatchConcurrentQueue action2 0 at <NSThread: 0x6000002ab200>{number = 7, name = (null)}"
"dispatchConcurrentQueue action1 0 at <NSThread: 0x6000002aa580>{number = 4, name = (null)}"
"dispatchConcurrentQueue action2 1 at <NSThread: 0x6000002ab200>{number = 7, name = (null)}"
"dispatchConcurrentQueue action1 1 at <NSThread: 0x6000002aa580>{number = 4, name = (null)}"
"dispatchConcurrentQueue action2 2 at <NSThread: 0x6000002ab200>{number = 7, name = (null)}"
"dispatchConcurrentQueue action2 3 at <NSThread: 0x6000002ab200>{number = 7, name = (null)}"
"dispatchConcurrentQueue action1 2 at <NSThread: 0x6000002aa580>{number = 4, name = (null)}"
"dispatchConcurrentQueue action1 3 at <NSThread: 0x6000002aa580>{number = 4, name = (null)}"
"dispatchConcurrentQueue barrier"
"dispatchConcurrentQueue action3 0 at <NSThread: 0x6000002ab200>{number = 7, name = (null)}"
"dispatchConcurrentQueue action4 0 at <NSThread: 0x6000002aa580>{number = 4, name = (null)}"
"dispatchConcurrentQueue action3 1 at <NSThread: 0x6000002ab200>{number = 7, name = (null)}"
"dispatchConcurrentQueue action4 1 at <NSThread: 0x6000002aa580>{number = 4, name = (null)}"
"dispatchConcurrentQueue action3 2 at <NSThread: 0x6000002ab200>{number = 7, name = (null)}"
"dispatchConcurrentQueue action4 2 at <NSThread: 0x6000002aa580>{number = 4, name = (null)}"
"dispatchConcurrentQueue action3 3 at <NSThread: 0x6000002ab200>{number = 7, name = (null)}"
"dispatchConcurrentQueue action4 3 at <NSThread: 0x6000002aa580>{number = 4, name = (null)}"
  • GCD 延遲執(zhí)行
func dispatchAfter() {
        debugPrint("\(Date())")
        DispatchQueue.global().asyncAfter(deadline: .now() + 2) {
            debugPrint("等了2 s\(Date())")
        }
    }
"2021-11-21 07:22:25 +0000"
"等了2 s2021-11-21 07:22:27 +0000"
  • DispatchGroup
func dispatchGroupNotify() {
        let dispatchGroup = DispatchGroup()
        let seralQueue = DispatchQueue(label: "dispatchSeralSync")
        seralQueue.async(group: dispatchGroup, execute: DispatchWorkItem(block: {
            print("dispatchGroup do\(Thread.current)")
        }))
        seralQueue.async(group: dispatchGroup, execute: DispatchWorkItem(block: {
            print("dispatchGroup do1\(Thread.current)")
        }))
        dispatchGroup.notify(queue: DispatchQueue.main, work: DispatchWorkItem(block: {
            print("dispatchGroup.notify(queue: DispatchQueue.main\(Thread.current)")
        }))
    }
dispatchGroup do<NSThread: 0x6000016acbc0>{number = 4, name = (null)}
dispatchGroup do1<NSThread: 0x6000016acbc0>{number = 4, name = (null)}
dispatchGroup.notify(queue: DispatchQueue.main<_NSMainThread: 0x6000016e81c0>{number = 1, name = main}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市趟咆,隨后出現(xiàn)的幾起案子添瓷,更是在濱河造成了極大的恐慌,老刑警劉巖值纱,帶你破解...
    沈念sama閱讀 216,324評(píng)論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件鳞贷,死亡現(xiàn)場離奇詭異,居然都是意外死亡虐唠,警方通過查閱死者的電腦和手機(jī)搀愧,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,356評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來疆偿,“玉大人咱筛,你說我怎么就攤上這事「斯剩” “怎么了迅箩?”我有些...
    開封第一講書人閱讀 162,328評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長处铛。 經(jīng)常有香客問我饲趋,道長,這世上最難降的妖魔是什么撤蟆? 我笑而不...
    開封第一講書人閱讀 58,147評(píng)論 1 292
  • 正文 為了忘掉前任奕塑,我火速辦了婚禮,結(jié)果婚禮上家肯,老公的妹妹穿的比我還像新娘龄砰。我一直安慰自己,他們只是感情好讨衣,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,160評(píng)論 6 388
  • 文/花漫 我一把揭開白布换棚。 她就那樣靜靜地躺著,像睡著了一般反镇。 火紅的嫁衣襯著肌膚如雪圃泡。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,115評(píng)論 1 296
  • 那天愿险,我揣著相機(jī)與錄音颇蜡,去河邊找鬼价说。 笑死,一個(gè)胖子當(dāng)著我的面吹牛风秤,可吹牛的內(nèi)容都是我干的鳖目。 我是一名探鬼主播,決...
    沈念sama閱讀 40,025評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼缤弦,長吁一口氣:“原來是場噩夢啊……” “哼领迈!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起碍沐,我...
    開封第一講書人閱讀 38,867評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤狸捅,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后累提,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體尘喝,經(jīng)...
    沈念sama閱讀 45,307評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,528評(píng)論 2 332
  • 正文 我和宋清朗相戀三年斋陪,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了朽褪。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,688評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡无虚,死狀恐怖缔赠,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情友题,我是刑警寧澤嗤堰,帶...
    沈念sama閱讀 35,409評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站度宦,受9級(jí)特大地震影響踢匣,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜斗埂,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,001評(píng)論 3 325
  • 文/蒙蒙 一符糊、第九天 我趴在偏房一處隱蔽的房頂上張望凫海。 院中可真熱鬧呛凶,春花似錦、人聲如沸行贪。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,657評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽建瘫。三九已至崭捍,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間啰脚,已是汗流浹背殷蛇。 一陣腳步聲響...
    開封第一講書人閱讀 32,811評(píng)論 1 268
  • 我被黑心中介騙來泰國打工实夹, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人粒梦。 一個(gè)月前我還...
    沈念sama閱讀 47,685評(píng)論 2 368
  • 正文 我出身青樓亮航,卻偏偏與公主長得像,于是被迫代替她去往敵國和親匀们。 傳聞我的和親對(duì)象是個(gè)殘疾皇子缴淋,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,573評(píng)論 2 353

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