Search code examples
objective-cmultithreadingcocoagrand-central-dispatch

What GCD queue, main or not, am I running on?


I am trying to write some thread safe methods so I am using:

...
dispatch_queue_t main = dispatch_get_main_queue();
dispatch_sync(main,^{
  [self doSomethingInTheForeground];
});
...

But If I am on the main thread that is not necessary, and I can skip all those dispatch calls, so I would like to know what thread I currently am on. How can I know this?

Or, perhaps it does not make difference (in performance) doing it?

Is it ok to do this comparison?

if (dispatch_get_main_queue() == dispatch_get_current_queue()){...}

Solution

  • Updated answer:

    The Apple docs have changed and now say "When called from outside of the context of a submitted block, this function returns the main queue if the call is executed from the main thread. If the call is made from any other thread, this function returns the default concurrent queue." so checking dispatch_get_main_queue() == dispatch_get_current_queue() should work.

    Original answer:

    Using dispatch_get_main_queue() == dispatch_get_current_queue() won't work. The docs for dispatch_get_current_queue say "When called outside of the context of a submitted block, this function returns the default concurrent queue". The default concurrent queue is not the main queue.

    [NSThread isMainThread] should work for what you want. Note that [NSThread isMainThread] can be true for for queues other than the main queue though, e.g., when calling dispatch_sync from the main thread.