Sobes.tech
Middle+

Can you provide an example of a situation where processes are mutually blocked, causing them to hang forever?

sobes.tech AI

Answer from AI

Deadlock occurs when two or more processes (or threads) simultaneously hold resources and each waits for the resource held by the other to be released. As a result, none of them can continue working.

Example:

  • Process A acquires resource R1.
  • Process B acquires resource R2.
  • Process A tries to acquire resource R2 and gets blocked, waiting for it to be released.
  • Process B tries to acquire resource R1 and also gets blocked.

Both processes wait for each other, leading to an infinite deadlock.

Example in C++ with mutexes:

#include <mutex>
#include <thread>
#include <iostream>

std::mutex mtx1, mtx2;

void thread1() {
    std::lock_guard<std::mutex> lock1(mtx1);
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    std::lock_guard<std::mutex> lock2(mtx2);
    std::cout << "Thread 1 acquired both locks\n";
}

void thread2() {
    std::lock_guard<std::mutex> lock2(mtx2);
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    std::lock_guard<std::mutex> lock1(mtx1);
    std::cout << "Thread 2 acquired both locks\n";
}

int main() {
    std::thread t1(thread1);
    std::thread t2(thread2);
    t1.join();
    t2.join();
    return 0;
}

In this example, deadlock can occur if thread1 acquires mtx1 and thread2 acquires mtx2, and both wait for each other.