Skip to content

Instantly share code, notes, and snippets.

@jspahrsummers
Created November 24, 2015 16:11
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jspahrsummers/af6ddfbabf3894bde981 to your computer and use it in GitHub Desktop.
Save jspahrsummers/af6ddfbabf3894bde981 to your computer and use it in GitHub Desktop.
[NSThread isMainThread] is probably not what you want!
#import <Foundation/Foundation.h>
int main (int argc, const char **argv) {
@autoreleasepool {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"is main thread? %i", (int)[NSThread isMainThread]);
});
});
dispatch_main();
}
return 0;
}
2015-11-24 16:08:39.545 main[88889:21446128] is main thread? 0
@adamkaplan
Copy link

Try again with UIApplicationMain() or NSApplicationMain(). In all apps environments this code prints "1" and it is safe to assume that blocks executed on the queue returned from dispatch_get_main_queue() will execute on the thread returned by [NSThread mainThread];

@jspahrsummers
Copy link
Author

@adamkaplan Good point, thanks.

@adamkaplan
Copy link

No problem :)

Interesting learnings from this: main thread pumps the main queue – not the other way around – since GCD only has a main queue, which by default, does nothing.

@tommycrush
Copy link

the main thread pumps the main queue – not the other way around – since GCD only has a main queue, which by default, does nothing.

What's that mean? Sorry, a bit of newb here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment