Skip to content

Instantly share code, notes, and snippets.

@jspahrsummers

jspahrsummers/main.m

Created Nov 24, 2015
Embed
What would you like to do?
[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

This comment has been minimized.

Copy link

@adamkaplan adamkaplan commented Nov 24, 2015

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

This comment has been minimized.

Copy link
Owner Author

@jspahrsummers jspahrsummers commented Nov 24, 2015

@adamkaplan Good point, thanks.

@adamkaplan

This comment has been minimized.

Copy link

@adamkaplan adamkaplan commented Nov 24, 2015

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

This comment has been minimized.

Copy link

@tommycrush tommycrush commented Nov 24, 2015

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