dispatch_sync死鎖問(wèn)題研究

首先,看看如下代碼的輸出是什么?

- (void)viewDidLoad {? ? [superviewDidLoad];NSLog(@"Hello");dispatch_sync(dispatch_get_main_queue(), ^{NSLog(@"World");? ? ? ? ? ? });}

首先答案是會(huì)發(fā)生死鎖,我們看看官方文檔關(guān)于dispatch_sync的解釋?zhuān)?/p>

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.

如果dispatch_sync()的目標(biāo)queue為當(dāng)前queue,會(huì)發(fā)生死鎖(并行queue并不會(huì))。使用dispatch_sync()會(huì)遇到跟我們?cè)趐thread中使用mutex鎖一樣的死鎖問(wèn)題。

話是這么說(shuō),我們看看究竟是怎么做的?先放碼:

source/queue.c

voiddispatch_sync(dispatch_queue_t dq,void(^work)(void)){structBlock_basic *bb = (void*)work;? ? dispatch_sync_f(dq, work, (dispatch_function_t)bb->Block_invoke);}DISPATCH_NOINLINEvoiddispatch_sync_f(dispatch_queue_t dq,void*ctxt, dispatch_function_t func){? ? typeof(dq->dq_running) prev_cnt;dispatch_queue_told_dq;if(dq->dq_width ==1) {returndispatch_barrier_sync_f(dq, ctxt, func);? ? }// 1) ensure that this thread hasn't enqueued anything ahead of this call// 2) the queue is not suspendedif(slowpath(dq->dq_items_tail) || slowpath(DISPATCH_OBJECT_SUSPENDED(dq))) {? ? ? ? _dispatch_sync_f_slow(dq);? ? }else{? ? ? ? prev_cnt = dispatch_atomic_add(&dq->dq_running,2) -2;if(slowpath(prev_cnt &1)) {if(dispatch_atomic_sub(&dq->dq_running,2) ==0) {? ? ? ? ? ? ? ? _dispatch_wakeup(dq);? ? ? ? ? ? }? ? ? ? ? ? _dispatch_sync_f_slow(dq);? ? ? ? }? ? }? ? old_dq = _dispatch_thread_getspecific(dispatch_queue_key);? ? _dispatch_thread_setspecific(dispatch_queue_key, dq);? ? func(ctxt);? ? _dispatch_workitem_inc();? ? _dispatch_thread_setspecific(dispatch_queue_key, old_dq);if(slowpath(dispatch_atomic_sub(&dq->dq_running,2) ==0)) {? ? ? ? _dispatch_wakeup(dq);? ? }}

Step1. 可以看到dispatch_sync將我們block函數(shù)指針進(jìn)行了一些轉(zhuǎn)換后,直接傳給了dispatch_sync_f()去處理。

Step2. dispatch_sync_f首先檢查傳入的隊(duì)列寬度(dq_width),由于我們傳入的main queue為串行隊(duì)列,隊(duì)列寬度為1,所有接下來(lái)會(huì)調(diào)用dispatch_barrier_sync_f,傳入3個(gè)參數(shù),dispatch_sync中的目標(biāo)queue、上下文信息和由我們block函數(shù)指針轉(zhuǎn)化過(guò)后的func結(jié)構(gòu)體。

接下來(lái)我們看看dispatch_barrier_sync_f的實(shí)現(xiàn)

source/queue.c

voiddispatch_barrier_sync_f(dispatch_queue_t dq, void *ctxt, dispatch_function_tfunc){? ? dispatch_queue_t old_dq = _dispatch_thread_getspecific(dispatch_queue_key);// 1) ensure that this thread hasn't enqueued anything ahead of this call// 2) the queue is not suspended// 3) the queue is not weirdif(slowpath(dq->dq_items_tail)? ? ? ? ? ? || slowpath(DISPATCH_OBJECT_SUSPENDED(dq))? ? ? ? ? ? || slowpath(!_dispatch_queue_trylock(dq))) {return_dispatch_barrier_sync_f_slow(dq, ctxt,func);? ? }_dispatch_thread_setspecific(dispatch_queue_key, dq);func(ctxt);? ? _dispatch_workitem_inc();? ? _dispatch_thread_setspecific(dispatch_queue_key, old_dq);? ? _dispatch_queue_unlock(dq);}

Step3. disptach_barrier_sync_f首先做了做了3個(gè)判斷:

隊(duì)列存在尾部節(jié)點(diǎn)狀態(tài)(判斷當(dāng)前是不是處于隊(duì)列尾部)

隊(duì)列不為暫停狀態(tài)

使用_dispatch_queue_trylock檢查隊(duì)列能被正常加鎖。

滿足所有條件則不執(zhí)行if語(yǔ)句內(nèi)的內(nèi)容,執(zhí)行下面代碼,簡(jiǎn)單解釋為:

使用mutex鎖,獲取到當(dāng)前進(jìn)程資源鎖。

直接執(zhí)行我們block函數(shù)指針的具體內(nèi)容。

然后釋放鎖,整個(gè)調(diào)用結(jié)束。

然后在我們例子中,很顯然當(dāng)前隊(duì)列中還有其他viewController的任務(wù),我們的流程跑到_dispatch_barrier_aync_f_slow()函數(shù)體中。

刨根問(wèn)底,讓我們看看這個(gè)函數(shù)。

source/queue.c

staticvoid_dispatch_barrier_sync_f_slow(dispatch_queue_tdq,void*ctxt,dispatch_function_tfunc){// It's preferred to execute synchronous blocks on the current thread// due to thread-local side effects, garbage collection, etc. However,// blocks submitted to the main thread MUST be run on the main threadstructdispatch_barrier_sync_slow2_s dbss2 = {? ? ? ? .dbss2_dq = dq,#ifDISPATCH_COCOA_COMPAT.dbss2_func = func,? ? ? ? .dbss2_ctxt = ctxt,#endif.dbss2_sema = _dispatch_get_thread_semaphore(),? ? };structdispatch_barrier_sync_slow_s {? ? ? ? DISPATCH_CONTINUATION_HEADER(dispatch_barrier_sync_slow_s);? ? } dbss = {? ? ? ? .do_vtable = (void*)DISPATCH_OBJ_BARRIER_BIT,? ? ? ? .dc_func = _dispatch_barrier_sync_f_slow_invoke,? ? ? ? .dc_ctxt = &dbss2,? ? };//---------------重點(diǎn)是這里---------------_dispatch_queue_push(dq, (void*)&dbss);? ? dispatch_semaphore_wait(dbss2.dbss2_sema, DISPATCH_TIME_FOREVER);? ? _dispatch_put_thread_semaphore(dbss2.dbss2_sema);#ifDISPATCH_COCOA_COMPAT// Main queue bound to main threadif(dbss2.dbss2_func ==NULL) {return;? ? }#endifdispatch_queue_told_dq = _dispatch_thread_getspecific(dispatch_queue_key);? ? _dispatch_thread_setspecific(dispatch_queue_key, dq);? ? func(ctxt);? ? _dispatch_workitem_inc();? ? _dispatch_thread_setspecific(dispatch_queue_key, old_dq);? ? dispatch_resume(dq);}

Step4. 既然我們上面已經(jīng)判斷了,main queue中還有其他任務(wù),現(xiàn)在不能直接執(zhí)行這個(gè)block,跳入到_dispatch_barrier_sync_f_slow函數(shù)體,那它怎么處理我們加入的block呢?

在_dispatch_barrier_sync_f_slow中,使用_dispatch_queue_push將我們的block壓入main queue的FIFO隊(duì)列中,然后等待信號(hào)量,ready后被喚醒。

然后dispatch_semaphore_wait返回_dispatch_semaphore_wait_slow(dsema, timeout)函數(shù),持續(xù)輪訓(xùn)并等待,直到條件滿足。

所以在此過(guò)程中,我們最初調(diào)用的dispatch_sync函數(shù)一直得不到返回,main queue被阻塞,而我們的block又需要等待main queue來(lái)執(zhí)行它。死鎖愉快的產(chǎn)生了。

最后:

我們繪制上張圖來(lái)輕松的描述一下這個(gè)問(wèn)題:

轉(zhuǎn)載:文/jackjhu ?原文鏈接:http://www.lxweimin.com/p/44369c02b62a?

最后編輯于
?著作權(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)容

  • 首先,看看如下代碼的輸出是什么? 首先答案是會(huì)發(fā)生死鎖,我們看看官方文檔關(guān)于dispatch_sync的解釋?zhuān)?S...
    jackjhu閱讀 12,941評(píng)論 6 56
  • 講清這個(gè)問(wèn)題需要理解以下幾個(gè)基本知識(shí) 線程是什么? GCD中隊(duì)列與任務(wù)是什么,sync和async方法是什么樣的機(jī)...
    minking1982閱讀 1,245評(píng)論 1 4
  • 簡(jiǎn)介 在iOS中,我們需要將非UI且耗時(shí)的任務(wù)放在主線程當(dāng)中執(zhí)行,同時(shí)確保在任務(wù)完成時(shí)進(jìn)行回調(diào)。常用的三種實(shí)現(xiàn)多線...
    adduct閱讀 402評(píng)論 0 1
  • 學(xué)習(xí)多線程,轉(zhuǎn)載兩篇大神的帖子,留著以后回顧!第一篇:關(guān)于iOS多線程,你看我就夠了 第二篇:GCD使用經(jīng)驗(yàn)與技巧...
    John_LS閱讀 638評(píng)論 0 3
  • 2017.11.27. 秀秀和她的伙伴有事外出了,今晚的九澍我守店。一樹(shù)燦花,伴著潺潺流水,角落的地?zé)簦持粕车?..
    可可Jane閱讀 334評(píng)論 0 0