我正在尝试更好地了解队列及其工作方式。这个片段是为了测试他们的行为:
- (void)dispatchQueueTest
{
NSLog( @"Begin test on %@ thread", [NSThread isMainThread] ? @"main" : @"other" );
dispatch_semaphore_t s = dispatch_semaphore_create(0);
dispatch_async( dispatch_get_main_queue(), ^{
NSLog( @"Signalling semaphore" );
dispatch_semaphore_signal(s);
});
NSLog( @"Waiting for worker" );
while( dispatch_semaphore_wait( s, DISPATCH_TIME_NOW ) ) {
NSDate* timeout = [NSDate dateWithTimeIntervalSinceNow:10.f];
// Process events on the run loop
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:timeout];
}
dispatch_release(s);
NSLog( @"All sync'd up" );
}
正如所料,它会在日志中生成:
Begin test on main thread
Waiting for worker
Signalling semaphore
All sync'd up
奇怪的是,如果从 UIViewController 的 (void)viewDidAppear:(BOOL)animated 调用此代码,那么它会改变行为。具体来说,它会因以下日志而死锁:
Begin test on main thread
Waiting for worker
我的问题是为什么 NSRunLoop runMode 在这种情况下不处理通过 dispatch_async 发送的块,但在其他情况下却处理?