我需要等待几个请求才能完成,然后才能继续执行下一个任务。 dispatch_group_t& dispatch_semaphore_t在这里非常相似。所以我想知道哪一个更好或者这里没有太大区别。
dispatch_group_t serviceGroup = dispatch_group_create();
dispatch_group_enter(serviceGroup);
// in completion block
dispatch_group_leave(serviceGroup);
//wait for all requests to complete
dispatch_group_notify(serviceGroup,dispatch_get_main_queue(),^{
// Won't get here until everything has finished
});
/* Or I can use dispatch_semaphore_t */
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
// in completion block
dispatch_semaphore_signal(sem);
// before start request
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
// Reaching here means all requests has completed
...
答案 0 :(得分:2)
在这种特殊情况下,关键区别在于信号量方法使调用dispatch_semaphore_wait
的线程保持活动状态,但在整个时间内被阻塞,而dispatch_group_notify
立即返回,仅稍后执行块,让调用线程可以自由地做其他事情。我会说在这种情况下dispatch_group_notify
是更好的方法。