Sobes.tech
Middle — Middle+

How is a deadlock situation prevented in multithreaded systems?

sobes.tech AI

Answer from AI

Deadlock occurs when multiple threads wait for resources held by each other, and none can proceed. The following approaches are used to prevent deadlock:

  1. Avoid cyclic dependencies: ensure that threads acquire resources in the same order.

  2. Use timeouts: when attempting to acquire a lock with a timeout, a thread can give up and release already acquired resources.

  3. Avoid nested locking: minimize the number of resources acquired simultaneously.

  4. Detection and recovery algorithms: periodically check for deadlocks and interrupt or restart threads.

An example in Python using ordered lock acquisition:

import threading

lock_a = threading.Lock()
lock_b = threading.Lock()

# Thread 1
with lock_a:
    with lock_b:
        # critical section
        pass

# Thread 2
with lock_a:  # acquire lock_a before lock_b to prevent deadlock
    with lock_b:
        # critical section
        pass

Here, both threads acquire locks in the same order, preventing deadlock.