Sobes.tech
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):

  1. Mutual Exclusion: Resources cannot be shared; only one process can use a resource at a time.
  2. Hold and Wait: A process holds at least one resource and waits to acquire additional resources held by others.
  3. No Preemption: Resources cannot be forcibly taken away from a process; they are released voluntarily.
  4. 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 sync on 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.")
    }
}
What is a deadlock? — iOS - sobes.tech