I'm quite confused.
Code below will cause a deadlock for sure:
// Will execute
DispatchQueue.main.async { // Block 1
// Will execute
DispatchQueue.main.sync { // Block 2
// Will not be executed
}
// Will not be executed
}
Because
- After we dispatch_async on main queue, it's submits the first block to the main queue to execute
- At some moment, the system decides to run block1
- The
.sync
method blocks "thread / queue?" <- My question - Because the "thread / queue" is blocked, block 2 can't execute before block 1 finishes, because Main queue is a serial queue, it execute task serially, one can't execute before another finishes
My question is: Does sync
block current thread it's executing on
or current queue
? (I understand the difference between thread & queue)
Most answers on the internet says it blocks thread
If block thread -> How come the
sync { }
block can still execute since the thread is blocked?If block queue -> Make more sense? Since the queue is blocked, we can't execute one before other finishes
I found some discussions about this:
dispatch_sync inside dispatch_sync causes deadlock
Difference Between DispatchQueue.sync vs DispatchQueue.async