Senior
What is a deadlock?
sobes.tech AI
Answer from AI
Deadlock is a situation in multithreaded or multiprocess systems where two or more threads (or processes) permanently block each other, waiting for resources held by each other.
Example: Thread A has acquired resource 1 and is waiting for resource 2, while Thread B has acquired resource 2 and is waiting for resource 1. Neither can continue working.
In C/C++, deadlock often occurs due to incorrect use of mutexes:
std::mutex m1, m2;
void thread1() {
std::lock_guard<std::mutex> lock1(m1);
// ...
std::lock_guard<std::mutex> lock2(m2);
// ...
}
void thread2() {
std::lock_guard<std::mutex> lock1(m2);
// ...
std::lock_guard<std::mutex> lock2(m1);
// ...
}
If thread1 acquires m1 and thread2 acquires m2, both will wait for each other, leading to deadlock.
To prevent deadlock, the following are used:
- fixed order of resource acquisition,
- timeouts,
- functions like
std::lockfor simultaneous acquisition of multiple mutexes.