7 Deadlock
7 Deadlock
#multithreading
[[(thread)]] [[1.th.parameters]] [[2.th.&return]] [[3.th.lambda]] [[4.th.methods]]
[[5.mutex]] [[6.mutex.lock_guard]] [[7.Deadlock]] [[8.recursive_mutex]] [[9.
unique_lock]]
---
Deadlock is a situation that arises in a multi-threaded program when two or more
threads are blocked and waiting for each other to release resources, resulting in a
standstill or a "deadlock". When a deadlock occurs, the threads involved are unable
to proceed, and the program may stop responding, resulting in a system crash.
2. Release locks as soon as possible: Holding onto locks for an extended period of
time increases the risk of deadlocks.
3. Use timeouts: Using timeouts on locks can prevent deadlocks by ensuring that a
thread doesn't wait indefinitely for a lock.
4. Avoid nested locks: Nested locks are a common cause of deadlocks, as they can
make it difficult to acquire locks in the correct order.
5. Use deadlock detection tools: There are many tools available for detecting
deadlocks in C++ programs, such as Valgrind and Helgrind.
## My Example
---
Deadlock:
```cpp
#include <iostream>
#include <mutex>
#include <thread>
#include "SimpleTimer.h"
mutex mtx1;
mutex mtx2;
void Print1() {
mtx2.lock();
mtx1.unlock();
mtx2.unlock();
void Print2() {
mtx1.lock();
mtx2.lock();
mtx1.unlock();
mtx2.unlock();
int main() {
SimpleTimer timer;
thread t1(Print1);
thread t2(Print2);
t1.join();
t2.join();
return 0;
}
```
Solution
```cpp
#include <iostream>
#include <mutex>
#include <thread>
#include "SimpleTimer.h"
mutex mtx1;
mutex mtx2;
void Print1() {
mtx1.lock();
mtx2.lock();
mtx1.unlock();
mtx2.unlock();
void Print2() {
mtx1.lock();
mtx2.lock();
mtx1.unlock();
mtx2.unlock();
SimpleTimer timer;
thread t1(Print1);
thread t2(Print2);
t1.join();
t2.join();
return 0;
}
```