Sobes.tech
Middle+

Mis juhtub, kui AppDelegate'is peamisel niidil kutsutakse 'dispatchQueue.main.sync'?

sobes.tech AI

Vastus AI-lt

A deadlock (mutual blocking) occurs.

Explanation:

  1. AppDelegate runs on the main thread.
  2. dispatchQueue.main.sync attempts 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 sync block to complete.
  4. The sync block cannot start because the main thread is occupied waiting.

In short, the main thread waits for the block to finish, and the block waits for the main thread to be free — a deadlock occurs. The application will freeze.

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
}