Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dispatch_sync call into a dispatch_async call

I get some doubts about behavior of this code :

dispatch_async(queue, ^{
    sleep(2);
    NSLog(@"step1");

    dispatch_sync(queue, ^{
        sleep(3);
        NSLog(@"step 2");
    });

    NSLog(@"step 3");
});

From these rows i expected to get as output step1 -> step3 -> step2 but i obtain only step1.

If i change dispatch_sync with dispatch_async it works as expected, Does dispatch_sync into a dispatch_async call create this kind of problem ?

Edit after answers ----------------

This case create a deadlock:

You can check accepted answer to have explanation of this situation and check this link for documentation http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dispatch_async.3.html

like image 668
MatterGoal Avatar asked Dec 29 '11 13:12

MatterGoal


2 Answers

That's a deadlock.

The dispatch_sync call will be waiting until queue is available before running its block and returning but that won't be available until the dispatch_async has finished so it will just sit there spinning waiting to call dispatch_sync.

like image 77
mattjgalloway Avatar answered Oct 14 '22 01:10

mattjgalloway


As mentioned by @mattjgalloway, it is a deadlock.

Apple's own documentation mentions the problem here: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dispatch_async.3.html (see "RECURSIVE LOCKS"). It is discussed in the context of recursive locks, but the principle is the same.

like image 33
Monolo Avatar answered Oct 14 '22 02:10

Monolo