Sobes.tech
Middle+

Kas saaksite anda näite olukorrast, kus protsesside vastastikune lukustamine põhjustab nende lõplikku seiskumist?

sobes.tech AI

Vastus AI-lt

Mutual lock (deadlock) occurs when two or more processes (or threads) simultaneously hold resources and each waits for the other to release a resource. As a result, none can continue.

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 has 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 has 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 the other to release the resource.