using dispatch_sync in Grand Central Dispatch using dispatch_sync in Grand Central Dispatch ios ios

using dispatch_sync in Grand Central Dispatch


You use it when you want to execute a block and wait for the results.

One example of this is the pattern where you're using a dispatch queue instead of locks for synchronization. For example, assume you have a shared NSMutableArray a, with access mediated by dispatch queue q. A background thread might be appending to the array (async), while your foreground thread is pulling the first item off (synchronously):

NSMutableArray *a = [[NSMutableArray alloc] init];// All access to `a` is via this dispatch queue!dispatch_queue_t q = dispatch_queue_create("com.foo.samplequeue", NULL);dispatch_async(q, ^{ [a addObject:something]; }); // append to array, non-blocking__block Something *first = nil;            // "__block" to make results from block availabledispatch_sync(q, ^{                        // note that these 3 statements...        if ([a count] > 0) {               // ...are all executed together...             first = [a objectAtIndex:0];  // ...as part of a single block...             [a removeObjectAtIndex:0];    // ...to ensure consistent results        }});


First understand its brother dispatch_async

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

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 somethingdispatch_sync(queue, ^{    //Do something else});//Do More Stuff

Here you got //Do something //Do something else and //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. Say you want to download large amount of data but you want to keep the UI smooth.

Hence, dispatch_sync is rarely used. But it's there. I personally never used that. Why not ask for some sample code or project that does use dispatch_sync.


dispatch_sync is semantically equivalent to a traditional mutex lock.

dispatch_sync(queue, ^{    //access shared resource});

works the same as

pthread_mutex_lock(&lock);//access shared resourcepthread_mutex_unlock(&lock);