Skip to content

Instantly share code, notes, and snippets.

@woolsweater
Created June 28, 2013 04:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woolsweater/5882484 to your computer and use it in GitHub Desktop.
Save woolsweater/5882484 to your computer and use it in GitHub Desktop.
Background queues sometimes execute their blocks on the main thread.
#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;
}
@rsaunders100
Copy link

This is very interesting - I get:

Sync on main: YES
Async on main: NO
Inner sync on main: NO
Inner sync on same as async: YES

@woolsweater
Copy link
Author

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