gpt4 book ai didi

objective-c - 等待 dispatch_semaphore 以等待许多异步任务完成的正确方法

转载 作者:行者123 更新时间:2023-12-03 23:32:11 26 4
gpt4 key购买 nike

我有一个异步方法 longRunningMethodOnObject:completion:

此方法接收“对象”类型的对象 - 使用其数据,然后调用完成处理程序。

我需要调用许多不同的“longRunningMethods”并等待全部完成。

我希望所有“longRunningMethodOnObject”在“for”循环中彼此异步(并行)运行。 (我不确定“longRunningMethodOnObject”是否彼此串行运行,但这是一个更普遍的问题)

我不确定我是否创建了正确的信号量,希望能解释一下在它们之间同步的正确方法。

包装函数的代码如下:

-(void)applyLongRunningOperationOnObjectInArray:(NSArray *)theObjects completion:(completion)block
{
// offsetting to worker thread in my object
dispatch_async(self.myQueue,^{
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); //Not sure if this should be here or in the for loop
for(Object *ob in theObjects)
{
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); // the semaphore for the "for" loop - should this be here? or above the for loop
[GlobalObject longRunningMethodOnObject:ob completion:^{ // would like each call to be independant of previous call in for loop
dispatch_semaphore_signal(semaphore); // signaling that it completed
}];
}
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); // would like to wait here for each semaphore
block(); // invoke the completion handler
});
}

最佳答案

我想你可以在这种情况下使用 dispatch_semaphore,但是调度组可能会使应用程序逻辑更简单:

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()

Concurrency Programming Guide作为关于这个话题的一点。向下滚动到“等待队列任务组”

要回答有关任务是否在队列中同时执行的问题,这取决于。在上面的例子中,_myQueue 是一个串行队列。全局命名队列是并发的。从 iOS 5 开始,您还可以使用 DISPATCH_QUEUE_CONCURRENT 队列类型创建并发队列。

关于objective-c - 等待 dispatch_semaphore 以等待许多异步任务完成的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19464356/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com