Why when calling

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { dispatch_sync(dispatch_get_main_queue(), ^{ NSLog(@"Hello world"); }); return YES; } 

The application will crash, but if there is no dispatch_async ?

  • It is not clear if in the method only return YES; , it falls, and if dispatch_async does, does it not fall? What error falls? - markov
  • Falls if you specify dispatch_sync . - Seryozha Kvyatkovskiy
  • 2
    Aah, damn it, did not notice that different dispatch_sync / dispatch_async was written. Well, yes, dispatch sync means to queue this block and freeze the current block until the block is executed in the main thread. And as current - this is the main one, then it turns out to sleep and not give control to anyone until that which we do not give control is fulfilled - markov

1 answer 1

Because dispatch_sync queues a function and blocks the current thread until the function executes and returns a value. Thus, if you do dispatch_sync on the current thread, you will get a deadlock - the current function waits for a response from a function that cannot start until the current function has completed.

From the apple documentation :

Submits a block to a dispatch queue for synchronous execution. Unlike dispatch_async, this function doesn’t return until the block has finished. Calling this function and targeting the current queue results in deadlock.