13
votes

This code

dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
      NSLog(@"Main Thread? %d", [NSThread isMainThread]);
});

shows that I'm in the main thread. Even doing this:

queue = dispatch_queue_create("nonMainQueue", NULL);

still reports that I'm in the main queue. This is, it seems, because I'm using dispatch sync.

Does this mean that my code is the same as not using dispatch_sync at all? Also: what's the point of dispatch_sync if it does nothing at all, then?

3
Queues != Threads.Richard J. Ross III
@RichardJ.RossIII that's the issue. I'm actually seeing (or imagining) an increase in performance using dispatch_sync. Am I out of my mind (since isMainThread returns YES in all cases)?Dan Rosenstark
try using dispatch_get_current_queue() == dispatch_get_main_queue() instead. You are not out of your mind, I promise :)Richard J. Ross III
Thanks Rob, I would try that if I wanted async. Thanks @RichardJ.RossIII, that's awesome. ` assert(dispatch_get_current_queue() != dispatch_get_main_queue() && "this better not be main");`Dan Rosenstark
here you have thread in apple dev forums where guys from apple are describing why it is deprecated and how to deal with itlupatus

3 Answers

11
votes

Because queues are not threads, in order to check if you are on the main 'queue', you must use different code, something similar to this:

if (dispatch_get_current_queue() == dispatch_get_main_queue()) {
   NSLog(@"On Main Thread!");
}

Just note that dispatch_get_current_queue is deprecated, and is subject to be completely removed in a later iOS/Mac OS version.

5
votes

This is documented behavior. As an optimization the blocks passed to dispatch_sync are executed on the current thread if possible (which is almost always).

1
votes

My understanding from Apple's GCD guide, there is no guarantee that dispatch queues will execute on a separate thread. GCD will determine which thread, and if necessary create a new one.

Part of the point is now you do not have to think about threads.

The only thing to keep in mind, is to make sure you are updating UI elements on the main queue, for example:

// on background queue
dispatch_async( dispatch_get_main_queue(), ^(void){
    someLabel.text = @"My Text";
});