-1

I am doing experiments with Grand Central Dispatch and have come across a crash on synchronous task.

func viewDidLoad() {
    super.viewDidLoad()

    self.testHello()
    print("Task2")
}

func testHello() {
    DispatchQueue.main.sync {
        print("Task1")
    }
}

Upon execution of above given function, I am facing crash.

Explanation on above crash will be appreciated.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Aman.Samghani
  • 2,151
  • 3
  • 12
  • 27
  • Please update your question (no comments) with the complete and exact error message and point out the exact line causing the crash. – rmaddy Nov 17 '18 at 16:27

1 Answers1

4

From DispatchQueue.sync documentation:

...this function does not return until the block has finished. Calling this function and targeting the current queue results in deadlock.

You are already on the main queue and you are forcing code to be executed synchronously on the main queue. The fact that you are on the main queue means that no other code can be executed on the queue right now, however, sync waits until that code is executed, therefore you are deadlocking the queue and you whole app.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • Thanks for wonderful explanation. But now question arise is if we use DispatchQueue.main.sync instead Async, why does it work? After all by writing DispatchQueue.main.Async line we are accessing main thread. – Aman.Samghani Nov 17 '18 at 17:02
  • 1
    `async` is not waiting for the block to be executed, therefore it will never cause a deadlock. Also it would not happen if the main queue were not serial. – Sulthan Nov 17 '18 at 17:43