when to use dispatch_sync

reference
http://stackoverflow.com/questions/4607125/using-dispatch-sync-in-grand-central-dispatch
http://stackoverflow.com/questions/9471420/whats-the-benefit-of-using-dispatch-sync-if-it-has-to-wait-until-the-main-threa?lq=1

First, let’s look at dispatch_async

You use dispatch_async to create a new thread. When you do that, the current thread will not stop.

That means:

Do More Stuff may be executed before Do something else finish.

What happens if you want the current thread to stop

You do not use dispatch at all. Just write the code normally

//Do something
//Do something else
//Do More Stuff

Now, say you want to do something on a DIFFERENT thread and yet wait as if and ensure that stuffs are done consecutively.

There are many reason to do this. UI update, for example, is done on main thread.

That’s where you use dispatch_sync

//Do something
dispatch_sync(queue, ^{
//Do something else
});
//Do More Stuff

Here you got

  1. Do something
  2. Do something else
  3. Do More stuff done consecutively

…..even though //Do something else is done on a different thread.

Usually, when people use different thread, the whole purpose is so that something can get executed without waiting.

An Example of using Dispatch_Sync

Say we have a mutable array.

We then create a custom queue q in order to take tasks to execute.

We throw some blocks on this custom queue q and process it via asynchronously via dispatch_async.

Now, say, we want to pull the first item off of the array. Then shift all the items over 1 spot to fill in the empty space. Hence, we’re rearranging all this data on the array….we can’t be letting other threads touch this array (i.e adding, deleting, updating…etc)

We gotta stop all activities on the queue that’s adding stuff to our array. That queue is q so we gotta synchronous on it.

We take off the 1st item like so:

We sync our taking off the 1st item with the other tasks in the queue. In other words, we make other tasks wait, execute taking off the 1st item, and let others continue.

Thus, this is an example of why we use dispatch_sync. We when we use sync, we block all other tasks on that queue. Let us finish our block. Then let the other tasks on that queue continue.

One More!

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:

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