7

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

2 Answers 2

21

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.