Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using dispatch_sync in Grand Central Dispatch

Can anyone explain with really clear use cases what the purpose of dispatch_sync in GCD is for? I can't understand where and why I would have to use this.

Thanks!

like image 739
Rasputin Jones Avatar asked Jan 05 '11 17:01

Rasputin Jones


2 Answers

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 available dispatch_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         } }); 
like image 81
David Gelhar Avatar answered Oct 10 '22 09:10

David Gelhar


First understand its brother dispatch_async

//Do something dispatch_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 something dispatch_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.

like image 34
user4951 Avatar answered Oct 10 '22 09:10

user4951