somtingwong
somtingwong

Reputation: 359

GCD deadlock on OS X but not on iOS

I have this code in my viewDidLoad

- (void)viewDidLoad {
    [super viewDidLoad];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    NSLog(@"First");
    dispatch_async(queue, ^{
        NSLog(@"Third");
        dispatch_sync(queue, ^{
            NSLog(@"Fourth");
        });
        NSLog(@"Last");
    });
    NSLog(@"Second");
}

which prints out:

2015-07-20 19:12:54.325 Test[7574:431705] First
2015-07-20 19:12:54.326 Test[7574:431736] Third
2015-07-20 19:12:54.326 Test[7574:431736] Fourth
2015-07-20 19:12:54.326 Test[7574:431705] Second
2015-07-20 19:12:54.326 Test[7574:431736] Last

This also differs on some executions. Sometimes it prints "First, Second, Third, Fourth, Last" and other times it produces the the output above.

Also, I have a test.m file with the following: #include

int main() {
  dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
  NSLog(@"First");
  dispatch_async(queue, ^{
      NSLog(@"Third");
      dispatch_sync(queue, ^{
          NSLog(@"Fourth");
        });
      NSLog(@"Last");
    });
  NSLog(@"Second");
  return 0;
}

And this produces:

2015-07-20 19:12:36.067 tester[7568:431388] First
2015-07-20 19:12:36.068 tester[7568:431388] Second

I don't understand why on the iOS Simulator it prints out all of the logs while on Mac it prints "First" and "Second" then deadlocks. I expected the iOS code to deadlock also but instead it prints out the "Third" and "Fourth". There isn't any other that deals with threading in the iOS code. Also when NSLog(@"First") is commented out, on some executions of test.m it produces something different as shown below:

$: ./tester
2015-07-20 19:19:31.030 tester[7608:433729] Second
$: ./tester
2015-07-20 19:19:32.268 tester[7609:433738] Third
2015-07-20 19:19:32.268 tester[7609:433737] Second
$ ./tester
2015-07-20 19:19:32.620 tester[7610:433740] Second
$: ./tester
2015-07-20 19:19:33.812 tester[7611:433744] Third
2015-07-20 19:19:33.812 tester[7611:433743] Second

I have no idea what is causing the difference in output. Is it the way iOS handles threading that differs from OS X? I would appreciate if anyone could explain what is going on

Upvotes: 1

Views: 73

Answers (1)

rmaddy
rmaddy

Reputation: 318814

On the Mac you do not have a deadlock. It is a simple case of main completing and the app terminating before the background thread has a chance to start or complete.

Keep in mind also that the order of seeing "Second" and "Third" in the log is undefined. By the time dispatch_async returns, you now have two concurrent threads so the NSLog on the main queue and the background queue could get output in either order.

If you block the main thread (such as using sleep) just before the return statement, you should see all logs from both threads.

Upvotes: 2

Related Questions