我正在努力更好地了解队列及其工作原理。这个片段用于测试他们的行为:
- (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
奇怪的是,如果这个代码是从 - (void)viewDidAppear:(BOOL)调用UIViewController的动画,那么它会改变行为。特别是它使用以下日志死锁:
Begin test on main thread
Waiting for worker
我的问题是为什么NSRunLoop runMode在这种情况下不会处理通过dispatch_async发送的块,但在其他情况下会这样做?
答案 0 :(得分:4)
我有一个项目,我将PlayerNameEntryViewController
推到导航控制器上。我在-[PlayerNameEntryViewController viewDidAppear:]
中放了一个断点。这是断点被击中时的堆栈跟踪:
#0 0x0002d3d3 in -[PlayerNameEntryViewController viewDidAppear:] at /Volumes/b/Users/mayoff/t/hotseat2/hotseat2/Home/PlayerNameEntryViewController.m:39
#1 0x00638fbf in -[UIViewController _setViewAppearState:isAnimating:] ()
#2 0x006392d4 in -[UIViewController __viewDidAppear:] ()
#3 0x006395d7 in -[UIViewController _endAppearanceTransition:] ()
#4 0x00648666 in -[UINavigationController navigationTransitionView:didEndTransition:fromView:toView:] ()
#5 0x007ee90e in -[UINavigationTransitionView _notifyDelegateTransitionDidStopWithContext:] ()
#6 0x007eec17 in -[UINavigationTransitionView _cleanupTransition] ()
#7 0x007eec86 in -[UINavigationTransitionView _navigationTransitionDidStop] ()
#8 0x005a2499 in -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] ()
#9 0x005a2584 in -[UIViewAnimationState animationDidStop:finished:] ()
#10 0x00497e00 in CA::Layer::run_animation_callbacks(void*) ()
#11 0x02e86515 in _dispatch_main_queue_callback_4CF ()
#12 0x015fe833 in __CFRunLoopRun ()
#13 0x015fddb4 in CFRunLoopRunSpecific ()
#14 0x015fdccb in CFRunLoopRunInMode ()
#15 0x01acd879 in GSEventRunModal ()
#16 0x01acd93e in GSEventRun ()
#17 0x00571a9b in UIApplicationMain ()
#18 0x00002461 in main at /Volumes/b/Users/mayoff/t/hotseat2/hotseat2/main.m:17
注意框架#11。这是对_dispatch_main_queue_callback_4CF
的致电。这是运行放在主队列上的块的函数。因此viewDidAppear:
实际上是从使用dispatch_async
添加到主队列的块内部调用的。
主队列是一个串行队列。串行队列的定义是一次只执行一个块的队列。如果队列正在执行块,则该队列上的其他块都不能启动。因此,当您以递归方式运行主运行循环时,运行循环会看到它已经在主队列上运行的块内,并且不会尝试启动更多块。这就是为什么你的信号量信令块永远不会运行而你的应用程序挂起的原因。
请注意,有时会从排队的块中调用viewDidAppear:
,有时则不会。你不应该依赖这两种行为。