iOS多線程的初步研究(十)-- dispatch同步

來源:互聯網
上載者:User

標籤:http   使用   os   io   strong   資料   for   ar   

GCD提供兩種方式支援dispatch隊列同步,即dispatch組和訊號量。

一、dispatch組(dispatch group

1. 建立dispatch組

dispatch_group_t group = dispatch_group_create();

2. 啟動dispatch隊列中的block關聯到group中

dispatch_group_async(group, queue, ^{

  // 。。。

});

3. 等待group關聯的block執行完畢,也可以設定逾時參數

dispatch_group_wait(group, DISPATCH_TIME_FOREVER);

4. 為group設定通知一個block,當group關聯的block執行完畢後,就調用這個block。類似dispatch_barrier_async。

dispatch_group_notify(group, queue, ^{

  // 。。。

});

5. 手動管理group關聯的block的運行狀態(或計數),進入和退出group次數必須匹配

dispatch_group_enter(group);

dispatch_group_leave(group);

所以下面的兩種調用其實是等價的,

A)

dispatch_group_async(group, queue, ^{

  // 。。。

});

B)

dispatch_group_enter(group);

dispatch_async(queue, ^{

  //。。。

  dispatch_group_leave(group);

});

所以,可以利用dispatch_group_enter、 dispatch_group_leave和dispatch_group_wait來實現同步,具體例子:http://stackoverflow.com/questions/10643797/wait-until-multiple-operations-executed-including-completion-block-afnetworki/10644282#10644282。

 

二、dispatch訊號量(dispatch semaphore

1. 建立訊號量,可以設定訊號量的資源數。0表示沒有資源,調用dispatch_semaphore_wait會立即等待。

dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

2. 等待訊號,可以設定逾時參數。該函數返回0表示得到通知,非0表示逾時。

dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

3. 通知訊號,如果等待線程被喚醒則返回非0,否則返回0。

dispatch_semaphore_signal(semaphore);

最後,還是回到產生消費者的例子,使用dispatch訊號量是如何?同步:

 

dispatch_semaphore_t sem = dispatch_semaphore_create(0);

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ //消費者隊列

while (condition) {

    if (dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, 10*NSEC_PER_SEC))) //等待10秒

      continue;

    //得到資料

  }

});

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ //生產者隊列

while (condition) {

    if (!dispatch_semaphore_signal(sem))

    {

      sleep(1); //wait for a while

      continue;

    }

    //通知成功

  }

});

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.