0
class ViewController: UIViewController {
   override func viewDidLoad() {
       // Do any additional setup after loading the view.
       DispatchQueue.main.sync { //this line crashes with Thread 1 : EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
          print("Rohit Kumar")
       }
   }
}

Getting crash with sync method in viewDidLoad but it is work with async, I don't know the reason behind this, can anyone help me in this.

I know the difference between sync and async.

Kamil.S
  • 5,205
  • 2
  • 22
  • 51
Rohit Kumar
  • 323
  • 3
  • 9

1 Answers1

7

The app crashes as you use sync inside main thread , what happens is code by default runs in main thread so when you dispatch code the usual is inside another queue not the main itself, this causes the queue to stop and wait until block inside {} is finished and as it's state is stopped/waiting then the code inside the block won't run hence a deadlock

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87