Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sync dispatch on current queue

I know you might find this an odd question, but I'm just learning GCD and I want to fully understand all its aspects. So here it is:

Is there ever any reason to dispatch a task SYNC on the CURRENT QUEUE?

For example:

    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(...);
    dispatch_async(concurrentQueue, ^{
       //this is work task 0

       //first do something here, then suddenly:

       dispatch_sync(concurrentQueue, ^{
               //work task 1
       });

       //continue work task 0
    });

I understand one thing: if instead of concurrentQueue I use a serial queue, then I get a deadlock on that serial queue, because work task 1 cannot start until the work task 0 is finished (because of the serial queue that guarantees order of execution), and in the same time work task 0 cannot continue its execution because it waits for the SYNC dispath function to return (please correct me if I'm wrong, that would make me a total noob).

So coming back to the original idea, is there any difference whatsoever between the code above and the same code where instead of calling the dispatch_sync function I simply write work task 1 code directly?

like image 573
Bogdan Alexandru Avatar asked Oct 04 '13 11:10

Bogdan Alexandru


People also ask

What are dispatch queues?

Dispatch queues are FIFO queues to which your application can submit tasks in the form of block objects. Dispatch queues execute tasks either serially or concurrently. Work submitted to dispatch queues executes on a pool of threads managed by the system.

What is synchronous vs asynchronous in GCD?

Synchronous means execution is blocked while waiting for a response. Asynchronous means execution continues immediately, and the response is delivered at some future time by a delegate callback, by executing a block/closure or whatever. Operation queues are often used to make synchronous things asynchronous.

What is DispatchQueue Global () async?

There are background threads for heavy tasks. DispatchQueue. global() runs these kind of tasks in background threads. You can tell the queue about how important your task is, so that DispatchQueue can prioritize your task. You can do this by providing Quality-of-Service information.

Is DispatchQueue global serial or concurrent?

The main dispatch queue is a globally available serial queue executing tasks on the application's main thread. As the main thread is used for UI updates it's important to be conscious when executing tasks on this queue.


1 Answers

No. I can't think of a reason to ever dispatch_sync on the same concurrent queue you're already on. If you do that, GCD will just immediately invoke your block, in-line, on the same thread, as if you had called it directly. (I checked.) And as you pointed out, doing that on a serial queue will deadlock you.

like image 62
ipmcc Avatar answered Oct 10 '22 11:10

ipmcc