dispatch_sync死鎖問題研究

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

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

首先答案是會發(fā)生死鎖购笆,我們看看官方文檔關(guān)于dispatch_sync的解釋:

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剃浇,會發(fā)生死鎖(并行queue并不會)拢切。使用dispatch_sync()會遇到跟我們在pthread中使用mutex鎖一樣的死鎖問題蒂萎。

話是這么說,我們看看究竟是怎么做的淮椰?先放碼:

source/queue.c

void
dispatch_sync(dispatch_queue_t dq, void (^work)(void))
{
    struct Block_basic *bb = (void *)work;
    dispatch_sync_f(dq, work, (dispatch_function_t)bb->Block_invoke);
}

DISPATCH_NOINLINE
void
dispatch_sync_f(dispatch_queue_t dq, void *ctxt, dispatch_function_t func)
{
    typeof(dq->dq_running) prev_cnt;
    dispatch_queue_t old_dq;

    if (dq->dq_width == 1) {
        return dispatch_barrier_sync_f(dq, ctxt, func);
    }

    // 1) ensure that this thread hasn't enqueued anything ahead of this call
    // 2) the queue is not suspended
    if (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首先檢查傳入的隊列寬度(dq_width),由于我們傳入的main queue為串行隊列泻拦,隊列寬度為1毙芜,所有接下來會調(diào)用dispatch_barrier_sync_f,傳入3個參數(shù)聪轿,dispatch_sync中的目標(biāo)queue爷肝、上下文信息和由我們block函數(shù)指針轉(zhuǎn)化過后的func結(jié)構(gòu)體。

接下來我們看看dispatch_barrier_sync_f的實現(xiàn)

source/queue.c

void
dispatch_barrier_sync_f(dispatch_queue_t dq, void *ctxt, dispatch_function_t func)
{
    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 weird
    if (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個判斷:

  • 隊列存在尾部節(jié)點狀態(tài)(判斷當(dāng)前是不是處于隊列尾部)
  • 隊列不為暫停狀態(tài)
  • 使用_dispatch_queue_trylock檢查隊列能被正常加鎖陆错。

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

  • 使用mutex鎖音瓷,獲取到當(dāng)前進(jìn)程資源鎖对嚼。
  • 直接執(zhí)行我們block函數(shù)指針的具體內(nèi)容。
  • 然后釋放鎖绳慎,整個調(diào)用結(jié)束纵竖。

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

刨根問底,讓我們看看這個函數(shù)珊楼。

source/queue.c

static void
_dispatch_barrier_sync_f_slow(dispatch_queue_t dq, void *ctxt, dispatch_function_t func)
{
    
    // 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 thread
    
    struct dispatch_barrier_sync_slow2_s dbss2 = {
        .dbss2_dq = dq,
#if DISPATCH_COCOA_COMPAT
        .dbss2_func = func,
        .dbss2_ctxt = ctxt,
#endif
        .dbss2_sema = _dispatch_get_thread_semaphore(),
    };
    struct dispatch_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,
    };
//---------------重點是這里---------------   
    _dispatch_queue_push(dq, (void *)&dbss);
    dispatch_semaphore_wait(dbss2.dbss2_sema, DISPATCH_TIME_FOREVER);
    _dispatch_put_thread_semaphore(dbss2.dbss2_sema);

#if DISPATCH_COCOA_COMPAT
    // Main queue bound to main thread
    if (dbss2.dbss2_func == NULL) {
        return;
    }
#endif
    dispatch_queue_t 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);
    dispatch_resume(dq);
}

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

在_dispatch_barrier_sync_f_slow中已慢,使用_dispatch_queue_push將我們的block壓入main queue的FIFO隊列中曲聂,然后等待信號量,ready后被喚醒佑惠。

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

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

最后:

我們繪制上張圖來輕松的描述一下這個問題:

dispatch_sync.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末察蹲,一起剝皮案震驚了整個濱河市请垛,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌洽议,老刑警劉巖宗收,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異亚兄,居然都是意外死亡混稽,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進(jìn)店門审胚,熙熙樓的掌柜王于貴愁眉苦臉地迎上來匈勋,“玉大人,你說我怎么就攤上這事膳叨∏⒔啵” “怎么了?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵菲嘴,是天一觀的道長饿自。 經(jīng)常有香客問我,道長龄坪,這世上最難降的妖魔是什么昭雌? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮健田,結(jié)果婚禮上烛卧,老公的妹妹穿的比我還像新娘。我一直安慰自己抄课,他們只是感情好唱星,可當(dāng)我...
    茶點故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著跟磨,像睡著了一般间聊。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上抵拘,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天哎榴,我揣著相機(jī)與錄音,去河邊找鬼僵蛛。 笑死尚蝌,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的充尉。 我是一名探鬼主播飘言,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼驼侠!你這毒婦竟也來了姿鸿?” 一聲冷哼從身側(cè)響起谆吴,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎苛预,沒想到半個月后句狼,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡热某,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年腻菇,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片昔馋。...
    茶點故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡筹吐,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出绒极,到底是詐尸還是另有隱情骏令,我是刑警寧澤,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布垄提,位于F島的核電站榔袋,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏铡俐。R本人自食惡果不足惜凰兑,卻給世界環(huán)境...
    茶點故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望审丘。 院中可真熱鬧吏够,春花似錦、人聲如沸滩报。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽脓钾。三九已至售睹,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間可训,已是汗流浹背昌妹。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留握截,地道東北人飞崖。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像谨胞,于是被迫代替她去往敵國和親固歪。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,724評論 2 354

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

  • 首先胯努,看看如下代碼的輸出是什么昼牛? - (void)viewDidLoad { [superviewDidLoad...
    made_China閱讀 857評論 0 2
  • 簡介 GCD(Grand Central Dispatch)是在macOS10.6提出來的术瓮,后來在iOS4.0被引...
    sunmumu1222閱讀 864評論 0 2
  • 講清這個問題需要理解以下幾個基本知識 線程是什么? GCD中隊列與任務(wù)是什么贰健,sync和async方法是什么樣的機(jī)...
    minking1982閱讀 1,234評論 1 4
  • 一. 重點: 1.dispatch_queue_create(生成Dispatch Queue) 2.Main D...
    BestJoker閱讀 1,585評論 2 2
  • 人生的枷鎖就是追求百分之百的安全感。 當(dāng)我們追求百分之百安全感的時候恬汁,我們沒有辦法集中精力去深入地思考伶椿,長期地思考...
    WindyLiu閱讀 620評論 4 3