Junior — Middle
Explain the concept of mutual locking of processes and how it can occur in a multithreaded system.
sobes.tech AI
Answer from AI
Deadlock is a situation in a multithreaded or multiprocess system where two or more processes (or threads) are waiting for resources held by each other, and none of them can continue.
Example of deadlock occurrence:
- Thread A acquires resource 1 and tries to get resource 2.
- Thread B acquires resource 2 and tries to get resource 1.
Both threads are waiting for the resource held by the other, and the system 'hangs'.
Deadlock usually requires four conditions to occur simultaneously:
- Mutual exclusion — resources cannot be shared.
- Hold and wait — a process holds a resource and waits for another.
- No preemption — resources can only be released by the process holding them.
- Circular wait — a cycle of processes each waiting for a resource held by the next.
In multithreaded systems, deadlock often occurs due to incorrect order of acquiring mutexes or other locks. To avoid deadlocks, the following are used:
- Acquiring resources in the same order in all threads.
- Using timeouts when waiting for locks.
- Detecting and recovering from deadlock.
Example in C++ with std::mutex:
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);
// work with resources
}
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);
// work with resources
}
Here, deadlock can occur if thread1 acquires mtx1 and thread2 acquires mtx2, and both wait for each other.