dispatch_group_t 或 dispatch_semaphore_t 等待多个异步请求完成

dispatch_group_t or dispatch_semaphore_t to wait for multiple async requests to complete

我需要等待几个请求完成才能继续下一个任务。 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
...

在这种特殊情况下,主要区别在于信号量方法使调用 dispatch_semaphore_wait 的线程保持活动状态,但会一直阻塞,而 dispatch_group_notify returns 会立即,只在稍后执行块,让调用线程自由地做其他事情。在这种情况下,我会说 dispatch_group_notify 是更好的方法。