需求:有4個(gè)任務(wù){(diào)1,2,3,4},執(zhí)行完前2個(gè)再執(zhí)行后2個(gè)
這里我們用到柵欄函數(shù)dispatch_barrier_(a)sync,(也可以用隊(duì)列組),我們要注意的是不能使用全局并發(fā)隊(duì)列(系統(tǒng)提供給我們的)否則會(huì)散失柵欄函數(shù)的意義
區(qū)別:先看官方文檔
dispatch_barrier_sync: Submits a barrier block object for execution and waits until that block completes.(提交一個(gè)柵欄函數(shù)在執(zhí)行中,它會(huì)等待柵欄函數(shù)執(zhí)行完)
dispatch_barrier_async: Submits a barrier block for asynchronous execution and returns immediately.(提交一個(gè)柵欄函數(shù)在異步執(zhí)行中,它會(huì)立馬返回)
作者理解:dispatch_barrier_sync 需要等待柵欄執(zhí)行完才會(huì)執(zhí)行柵欄后面的任務(wù),而dispatch_barrier_async 無(wú)需等待柵欄執(zhí)行完,會(huì)繼續(xù)往下走(保留在隊(duì)列里)
原因:在同步柵欄時(shí)柵欄函數(shù)在主線程中執(zhí)行,而異步柵欄中開(kāi)辟了子線程?hào)艡诤瘮?shù)在子線程中執(zhí)行
1.先來(lái)看看dispatch_barrier_sync
打印:
再次打印:
得到結(jié)果:柵欄函數(shù)確實(shí)分割了任務(wù),但是任務(wù)執(zhí)行的順序的確是無(wú)序的(異步函數(shù))
2.換成dispatch_barrier_async
打印:
再次打印:
特別注意:
The queue you specify should be a concurrent queue that you create yourself using the dispatch_queue_create function. If the queue you pass to this function is a serial queue or one of the global concurrent queues, this function behaves like the dispatch_sync function.
官方說(shuō)明大意:在使用柵欄函數(shù)時(shí).使用自定義隊(duì)列才有意義,如果用的是串行隊(duì)列或者系統(tǒng)提供的全局并發(fā)隊(duì)列,這個(gè)柵欄函數(shù)的作用等同于一個(gè)同步函數(shù)的作用