1

Look at these two slightly similar cases:

case 1:

func test() {
  DispatchQueue.global().sync {
    print("a")
    DispatchQueue.main.sync {
        print("b")
    }
  }
}

and case 2:

func test() {
    DispatchQueue.main.async {
        print("a")
        DispatchQueue.main.sync {
            print("b")
        }
    }
}

In the first case the code crashes with

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP,...

the explaination for that acc to me is that in the first case the task is submitted synchronoulsy on the global queue using DispatchQueue.global().sync . Given the the function test() itself was called from the main queue, the main queue will wait for the task added in *DispatchQueue.global().sync to finish. However, it encounter another task added synchronously to the main queue DispatchQueue.main.sync { print("b") } . Now the task that's running on the main queue is blocked waiting for this new task that's again running on the main queue to complete. Hence, deadlock which causes the crash.

In the second case, it is somewhat similar to the first, However, there is no crash even though the task print("b") is added to main serial queue synchronoulsy (which is inside test() method which is itself called from the main queue) but it is still causing deadlock which is evident from the fact that "a" is printed but "b" is not printed in the second case.

I need to understand why there was no crash in this case (on playground)

Romit Kumar
  • 2,442
  • 6
  • 21
  • 34

1 Answers1

1

If you jump to the top of that stack trace resulting from that EXC_BAD_INSTRUCTION and it will tell you precisely what the issue was:

enter image description here

Why your second example did not generate a EXC_BAD_INSTRUCTION, I cannot say, as it does on my computer.

That having been said, most deadlocks simply do not generate a nice EXC_BAD_INSTRUCTION for you. Often it just freezes. Why your second was not caught by the same diagnostic is unclear. But you should not be relying upon this EXC_BAD_INSTRUCTION, anyway, as it only catches one particular deadlock risk...

Rob
  • 415,655
  • 72
  • 787
  • 1,044