9

Why would anyone ever use dispatch_sync if the block has to wait until the main thread finishes. What is the benefit of using this function rather than writing code in-line (non-block and outside of Grand Central Dispatch). I may be misunderstanding what dispatch_sync actually does. Thanks.

Ryan
  • 2,650
  • 3
  • 29
  • 43
  • 1
    possible duplicate: http://stackoverflow.com/questions/4607125/usage-of-dispatch-sync-in-grand-central-dispatch – UIAdam Feb 27 '12 at 20:02

2 Answers2

7

dispatch_sync does what you think — it posts the block to the nominated queue and blocks the current queue until the block has been performed. The main queue/thread isn't specifically involved unless you're either dispatching to it or from it.

So, you'd generally use it if an operation had to be performed on a different queue/thread — such as a SQLite or OpenGL operation — but you either needed the result of the operation or simply needed to know that the operation was complete for functionality terms.

The pattern:

    dispatch_async(otherQueue,
    ^{
           id result = doHardTask();

           dispatch_async(originalQueue,
               ^{
                     didGetResult(result);
               });
    });

is better practice but isn't really something you can just glue on at the end.

Shaik Riyaz
  • 11,204
  • 7
  • 53
  • 70
Tommy
  • 99,986
  • 12
  • 185
  • 204
  • Oh, so when you nominate a queue, this really is a secondary queue (i.e. not the main queue of my app and wouldn't cause a lockup). So, if I use all dispatch_sync blocks, I still get the benefit of running on a secondary thread. That right? – Ryan Feb 27 '12 at 21:10
  • 1
    dispatch_sync effectively adds the time cost of the block to two queues instead of one (though the processing occurs only once). So you'd get no inherent user interaction benefit from using `dispatch_sync` on your main thread. – Tommy Feb 27 '12 at 22:33
0

You could use dispatch_async to launch a concurrent queue and within the block associated with that call you could use dispatch_sync to launch a series of tasks on a second queue. This would all occur without blocking the main queue.

  • Is there any point to using a dispatch_sync if I'm using all dispatch_sync though? I'm looking at someone's code and that's all they use. Seems like you could do the same thing without the blocks. No? – Ryan Feb 27 '12 at 20:18
  • Off hand, I can't think of an occasion when you'd use dispatch_sync outside of a block dispatched with dispatch_async, as Tommy's code illustrates. – StephenAshley.developer Feb 28 '12 at 00:10