【发布时间】:2013-10-19 09:08:44
【问题描述】:
我有一个异步方法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_release 来释放它对信号量对象的引用并最终释放它的内存。" - dispatch_semaphore_create
标签: objective-c asynchronous grand-central-dispatch semaphore