Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why dispatch_sync( ) call on main queue is blocking the main queue?

I know this is not a strong question but I have to clear my mind on this concept.

I have defined myBlock as follows.

void(^myBlock)(void) = ^{
   for(int i = 0;i < 10 ; i++)
   {
       NSLog(@"%d and current queue = %@",i,[NSThread currentThread]);
   } 
};

Now In viewDidLoad method when I uses the dispatch_sync() method independently on main queue then the main queue gets blocked.

Here is the Sample.

- (void)viewDidLoad
 {
    [super viewDidLoad];
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_sync(queue,myBlock);
 }

But But, when I use the same dispatch_sync() function on main thread Inside a block of dispatch_async() function which is fired on concurrent queue then the main thread does not blocked.

Here is the sample.

- (void)viewDidLoad
 {
    [super viewDidLoad];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_async(queue,^{  

        dispatch_sync(dispatch_get_main_queue(),myBlock);
    });
 }

I am not clear why this is happening? Why main thread blocked when calling dispatch_sync() independently?

like image 211
Bhavesh Avatar asked Sep 11 '13 12:09

Bhavesh


2 Answers

When using dispatch_sync on a serial queue (like the main queue) the current thread has to wait until the dispatched code is executed.

A dead lock occurs when a block is dispatched synchronously on from a serial queue to the same queue.

like image 146
Nikolai Ruhe Avatar answered Oct 04 '22 11:10

Nikolai Ruhe


There is only one main queue. In your first example, viewDidLoad is running on it. You then tell viewDidLoad to wait (i.e. "sync") on something else that's going to run on the main queue. They both can't be on it at exactly the same time.

In your second example, it's the concurrent queue that's being told to wait. That's not a problem because by doing dispatch_async, viewWillLoad is giving up the main queue and making it available for your block to run.

like image 23
Phillip Mills Avatar answered Oct 04 '22 12:10

Phillip Mills