我试图更好地了解队列及其工作原理。这个片段是为了测试他们的行为:
- (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" );
}
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,它会在日志中生成以下内容:
Begin test on main thread
Waiting for worker
Signalling semaphore
All sync'd up …Run Code Online (Sandbox Code Playgroud)