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!
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 } });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With