correct way to wait for dispatch_semaphore in order to wait for many async tasks to complete

你离开我真会死。 提交于 2019-12-04 17:02:05

I suppose you could use dispatch_semaphore in this case, but dispatch groups may make the application logic simpler:

NSArray *theObjects = @[@"Apple",@"Orange",@"Peach"];
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t _myQueue = dispatch_queue_create("com.cocoafactory.DispatchGroupExample",
                                                      0);
for( id ob in theObjects ) {
    dispatch_group_async(group, _myQueue, ^{
        //  do some long running task.
    });
}
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);

//  now do whatever should be done after
//  all of your objects are processed
//  in your case block()

The Concurrency Programming Guide as a bit on this topic. Scroll down to 'Waiting on Groups of Queued Tasks"

To answer the question about whether tasks are execute concurrently in the queue or not, it depends. In the example above, _myQueue is a serial queue. The global named queues are concurrent. You can also create concurrent queues with the DISPATCH_QUEUE_CONCURRENT queue type as of iOS 5.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!