Sobes.tech
Middle+

What happens if you call 'dispatchQueue.main.sync' on the main thread in AppDelegate?

sobes.tech AI

Answer from AI

Deadlock will occur.

Explanation:

  1. AppDelegate runs on the main thread.
  2. dispatchQueue.main.sync tries to execute code on the main thread synchronously, i.e., it waits for the code block to finish.
  3. But the main thread is already busy executing AppDelegate and is waiting for the block in sync to complete.
  4. The block in sync cannot start executing because the main thread is busy waiting.

As a result, the main thread waits for the block to execute, and the block waits for the main thread to be free — a deadlock occurs. The application will hang.

Example code that causes Deadlock:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    print("Application started")

    // This call will cause Deadlock
    DispatchQueue.main.sync {
        print("This code will never be executed")
    }

    print("This code will also not be reached")

    return true
}
What happens if you call 'dispatchQueue.main.sync' on… - sobes.tech