For learning purposes, declared a DispatchQueue
inside the demo project.
When I tap the button, the "Statement 1" is printed in the console and after a few seconds the application crashes with the error:
Thread 8: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
I know that asynchronous means that the two things don't know or care when the other is happening. Sync implies that two things must occur at the same time, or alternatively, that one of them must wait until the other one catches up.
Can anyone explain why the app crashed?
@IBAction func queuePrint(_ sender: UIButton) {
let queue = DispatchQueue(label: "io.myQueue.queue")
queue.async {
print("Statement 1")
queue.sync {
print("Statement 2")
queue.async {
print("Statement 3")
}
}
}
queue.async {
print("Statement 4")
}
queue.async {
print("Statement 5")
}
}
CodePudding user response:
You initialize new DispatchQueue
like below:
let queue = DispatchQueue(label: "io.myQueue.queue") // Serial by default
Your queue is Serial, only one Thread can run at the same time. So you when you call queue.sync inside its scope (you call it in queue.async) it will cause a deadlock, because there is no new Thread to execute your code inside queue.sync, your queue is Serial, not Concurrent. Serial Queue or Serial Dispatch Queue is FIFO (First In, First Out).
So you can change it to this:
`let queue = DispatchQueue(label: "io.myQueue.queue", attributes: .concurrent)`
Ref: https://developer.apple.com/documentation/dispatch/dispatchqueue/attributes