dispatch_barrier_async的作用

作用

  • 實現高效率的數據庫訪問和文件訪問
  • 避免數據競爭

前提條件

  • 必須使用dispatch_queue_create 創建隊列
  • 且隊列屬性為 DISPATCH_QUEUE_CONCURRENT
    (注意:使用 dispatch_barrier_async,該函數只能搭配自定義并行隊列 dispatch_queue_t 使用。不能使用: dispatch_get_global_queue,否則 dispatch_barrier_async 的作用會和 dispatch_async 的作用一模一樣。 )
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        NSLog(@"--1---%@",[NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"--2---%@",[NSThread currentThread]);
    });
    dispatch_barrier_async(queue, ^{
        NSLog(@"--barrier---%@",[NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"--3---%@",[NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"--4---%@",[NSThread currentThread]);
    });

結果

2017-06-30 17:34:11.889 test[50672:716568] --1---<NSThread: 0x6080000792c0>{number = 3, name = (null)}
2017-06-30 17:34:11.889 test[50672:716586] --2---<NSThread: 0x600000079f80>{number = 4, name = (null)}
2017-06-30 17:34:11.889 test[50672:716586] --barrier---<NSThread: 0x600000079f80>{number = 4, name = (null)}
2017-06-30 17:34:11.889 test[50672:716586] --3---<NSThread: 0x600000079f80>{number = 4, name = (null)}
2017-06-30 17:34:11.889 test[50672:716568] --4---<NSThread: 0x6080000792c0>{number = 3, name = (null)}

其中 --barrier--- 前的和后的是不確定的,但3,4 一定在1,2 后面執行
參考鏈接

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 在這篇文章中,我將為你整理一下 iOS 開發中幾種多線程方案,以及其使用方法和注意事項。當然也會給出幾種多線程的案...
    張戰威ican閱讀 615評論 0 0
  • 概述 這篇文章中,我不會說多線程是什么、線程和進程的區別、多線程有什么用,當然我也不會說什么是串行、什么是并行等問...
    hashakey閱讀 310評論 0 0
  • 文章目錄GCD簡介任務和隊列GCD的使用步驟隊列的創建方法任務的創建方法GCD的基本使用并行隊列 + 同步執行并行...
    lusen_b閱讀 253評論 0 1
  • 這下知道為什么像KEEP這樣的APP這么受歡迎,因為它作用了觀察、分類、定義,三部曲。 它先讓用戶輸入自己的體重身...
    Janet大昕鼓徵閱讀 225評論 0 7
  • 清明時節 天空若還下著小雨 若你還能來到我墳前 那就請你不要撐著傘 請抬頭看著天空 那是我的眼淚 我對你無盡的思念…
    割心的愛閱讀 184評論 1 1