Created
June 28, 2013 04:38
-
-
Save woolsweater/5882484 to your computer and use it in GitHub Desktop.
Background queues sometimes execute their blocks on the main thread.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
int main(int argc, const char * argv[]) | |
{ | |
@autoreleasepool { | |
dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); | |
dispatch_sync(q, ^{ | |
NSLog(@"Sync on main: %@", [NSThread isMainThread] ? @"YES" : @"NO"); | |
}); | |
dispatch_queue_t q2 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); | |
dispatch_async(q, ^{ | |
NSThread * origThread = [NSThread currentThread]; | |
NSLog(@"Async on main: %@", [NSThread isMainThread] ? @"YES" : @"NO"); | |
dispatch_sync(q2, ^{ | |
NSLog(@"Inner sync on main: %@", [NSThread isMainThread] ? @"YES" : @"NO"); | |
NSLog(@"Inner sync on same as async: %@", [[NSThread currentThread] isEqual:origThread] ? @"YES" : @"NO"); | |
}); | |
}); | |
dispatch_main(); | |
} | |
return 0; | |
} |
Yes indeedy; those are the expected values, @rsaunders100. The queue avoids doing an expensive context switch in the "sync" case, because the originating thread has to wait anyways.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is very interesting - I get: