Skip to content
Deadlock — Explained with Examples

Deadlock — Explained with Examples

DodaTech Updated Jun 15, 2026 2 min read

Deadlock occurs when two or more threads are blocked forever, each waiting for a resource held by another thread in a circular chain.

Deadlock requires four conditions (Coffman conditions): mutual exclusion (resources cannot be shared), hold and wait (threads hold resources while waiting for others), no preemption (resources cannot be forcibly taken), and circular wait (a cycle of waiting threads). Prevention strategies include acquiring locks in a fixed global order, using try-lock with timeouts, or using lock-free programming.

Think of a deadlock like two cars facing each other on a narrow one-lane bridge. Neither can move forward because the other occupies the space. Neither backs up. They are stuck indefinitely. The only solution is an external intervention (prevention strategy) or one driver signaling the other.

Deadlock can be prevented by ensuring at least one Coffman condition never holds. The most practical approach is enforcing lock ordering — all threads acquire locks in the same sequence.

import threading
import time

# Example that CAN deadlock
def thread_a(lock1, lock2):
    with lock1:
        print("Thread A acquired lock1")
        time.sleep(0.1)
        with lock2:
            print("Thread A acquired lock2")

def thread_b(lock1, lock2):
    with lock2:
        print("Thread B acquired lock2")
        time.sleep(0.1)
        with lock1:
            print("Thread B acquired lock1")

# Deadlock avoidance: fixed lock order
def thread_a_safe(lock1, lock2):
    # Always acquire locks in same order
    first, second = sorted([lock1, lock2], key=id)
    with first:
        time.sleep(0.1)
        with second:
            print("Thread A done safely")

def thread_b_safe(lock1, lock2):
    first, second = sorted([lock1, lock2], key=id)
    with first:
        time.sleep(0.1)
        with second:
            print("Thread B done safely")

Use tools like lock ordering, timeout-based lock acquisition, or deadlock detection (wait-for graphs) to manage deadlock risk in complex systems.

Mutex, Race Condition, Semaphore, Critical Section, Lock-Free Programming

Race Conditions

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro