標籤: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;
}
//通知成功
}
});