Junior
What is a deadlock?
sobes.tech AI
Answer from AI
A deadlock is a state where two or more threads or processes are blocked, each waiting for the other to release a resource, causing all of them to be stuck.
The four necessary conditions for a deadlock (Coffman conditions):
- Mutual Exclusion: Resources cannot be shared; only one process can use a resource at a time.
- Hold and Wait: A process holds at least one resource and waits to acquire additional resources held by others.
- No Preemption: Resources cannot be forcibly taken away from a process; they are released voluntarily.
- Circular Wait: A set of processes are waiting for each other in a circular chain.
In iOS development, deadlocks often occur when working with concurrency, such as improper use of GCD or Operation Queues:
- Attempting to perform a synchronous task on a queue that is already executing on the current thread (e.g., calling
syncon the main queue from the main thread). - Two threads trying to acquire two different locks or semaphores in different orders.
Example of a simple deadlock with GCD:
func deadlockExample() {
// Main queue
let mainQueue = DispatchQueue.main
// Perform a synchronous block on the main queue from the main thread
// Main thread waits for the block to finish,
// but the block cannot start because the main thread is busy waiting.
mainQueue.sync {
print("This line will never be reached.")
}
}