好的,我最终使用了我自己的解决方案,使用 GCD 的块通知组。我还使用了串行队列(而不是并发),它保证我们只创建 1 个额外的线程。
@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);
}