why are GCD calls nested?

There seems to be a convention regarding nesting GCD calls... for example



dispatch_queue_t queue = dispatch_queue_create("com.test123", NULL);

dispatch_queue_t main = dispatch_get_main_queue();

dispatch_async(queue,

^{

[self methodNotMainThread];

dispatch_async(main, ^{ [self methodMainThread]; });

});

___


is that different from:


dispatch_async(queue,

^{ [self methodNotMainThread]; });

dispatch_async(main,

^{ [self methodMainThread]; });


what is the purpose of nesting here?

Accepted Reply

If you don't nest that way, then -methodMainThread may start before -methodNotMainThread has completed. The intent is to avoid that, presumably because the former depends on the latter.

Replies

Some operations can only be executed on the main thread. Other operations may need to access shared data via a serial queue.

If you don't nest that way, then -methodMainThread may start before -methodNotMainThread has completed. The intent is to avoid that, presumably because the former depends on the latter.

Ah, that makes sense. Okay... thanks!

I bet not, because those are both serial queues.

Whether the queues are serial or concurrent doesn't matter, unless they are the same queue (or target a common serial queue). What matters is that the blocks are dispatched asynchronously. If the calls are not nested, the first block is queued but execution of the code shown immediately continues and queues the second block, too. Both blocks are free to execute from that point on.

If the queues are serial, then when the blocks are free to execute can depend on where they are called from, because they are serial. Given the OP's other posts, I'm pretty sure all this is being executed from the main queue. My goal was trying to explain concurrency, why some operations need to be on the main thread, and how "nesting" is used to achieve that.


But that is really not the issue here. The issue is that the OP is getting confused going back and forth between here and Stack Overflow. The subtle distinctions of when a block is enqueued vs. executed are not all that important right now.


I think I have found the source of the OP's confusion in this case. One of the Stack Overlow threads referenced in the OP's other thread appears to show the "un-nested" code. So, this would be a logical question. Why do one instead of the other? But upon closer inspection, the original Stack Overlow example (near the bottom of stackoverflow.com/questions/7290931/gcd-threads-program-flow-and-ui-updating) is also "nested". It is just poorly indented. It is reasons like this that beginners need to focus on the basics before the subtleties.