在iOS中,什么等同于win32的WaitForMultipleObjects函数?
这大致就是我想要的:
NSCondition *condition1;
NSCondition *condition2;
NSCondition *condition3;
wait_for_conditions([NSArray arrayWithObjects: condition1, condition2, condition3, nil],
^{
// Some code which must be executed when all conditions were fired
});
// in some other places of program:
[condition1 signal];
// ...
[condition2 signal];
// ...
[condition3 signal];在iOS中实现这一点的方法有哪些?
编辑:我不受NSCondition使用的限制,任何其他同步的事情都会好的(我刚刚在谷歌上搜索并找到了NSCondition)。
发布于 2012-05-21 21:25:15
好的,我最终使用了我自己的解决方案,使用了GCD的分组通知。我还使用了串行队列(而不是并发),这保证了我们只创建了一个额外的线程。
@interface WaitCondition : NSObject
- (void) fire;
@end
@implementation WaitCondition {
BOOL fired;
NSCondition *condition;
}
- (id) init
{
if ((self = [super init])) {
condition = [NSCondition new];
}
return self;
}
- (void) fire
{
[condition lock];
[condition signal];
fired = YES;
[condition unlock];
}
- (void) wait
{
[condition lock];
while (!fired) {
[condition wait];
}
[condition unlock];
}
@end
void Dispatch_NotifyForConditions(NSArray *conditions, dispatch_block_t completion)
{
dispatch_queue_t queue = dispatch_queue_create("notify_queue", NULL);
dispatch_group_t group = dispatch_group_create();
for (WaitCondition *condition in conditions)
{
NSCAssert([condition isKindOfClass:[WaitCondition class]], @"Dispatch_NotifyForConditions: conditions must contain WaitCondition objects only.");
dispatch_group_async(group, queue, ^{
[condition wait];
});
}
dispatch_group_notify(group, queue, completion);
dispatch_release(queue);
dispatch_release(group);
}发布于 2012-05-17 19:46:12
您可以为每个条件创建一个具有唯一通知名称的NSNotifications。然后,对于每个通知,都将调用相同的函数。
发布于 2012-05-17 20:23:13
那这个呢?
void async(void (^block)())
{
[NSThread detachNewThreadSelector:@selector(invoke) toTarget:[block copy] withObject:nil];
}
__attribute__((sentinel(NULL)))
void wait_for_conditions(void (^block)(), NSCondition *condition, ...)
{
va_list args;
va_start(args, condition);
NSMutableArray *conditions = [NSMutableArray array];
do {
[conditions addObject:condition];
} while ((condition = va_arg(args, NSCondition *)));
va_end(args);
NSCondition *overallCondition = [NSCondition new];
for (int i = 0; i < conditions.count; i++) {
NSCondition *cond = [conditions objectAtIndex:i];
async(^{
[cond lock];
[cond wait];
[cond unlock];
[overallCondition lock];
[overallCondition signal];
[overallCondition unlock];
});
}
for (int i = 0; i < conditions.count; i++) {
[overallCondition lock];
[overallCondition wait];
[overallCondition unlock];
}
if (block)
block();
}显然,这有一个缺点,那就是有效地使你的线程翻倍,但我不知道是否有更简单的方法来实现这一点。
https://stackoverflow.com/questions/10634083
复制相似问题