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:
AppDelegateruns on the main thread.dispatchQueue.main.synctries to execute code on the main thread synchronously, i.e., it waits for the code block to finish.- But the main thread is already busy executing
AppDelegateand is waiting for the block insyncto complete. - The block in
synccannot 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
}