Home >Backend Development >C++ >Deadlock in C++ concurrent programming and strategies to avoid deadlock?
Deadlock occurs when a thread falls into a circular waiting state while waiting for other threads to release resources. Strategies to avoid deadlock include: Avoid loop waiting Orderly use of resources Timeout strategy In the dining philosophers problem, orderly use of chopstick resources (left chopstick first) solves the deadlock problem.
Deadlock in C++ concurrent programming and strategies to avoid deadlock
What is a deadlock?
In concurrent programming, deadlock occurs when multiple threads wait for other threads to release resources at the same time. This causes the thread to block indefinitely, unable to continue execution.
Strategies to avoid deadlock
There are several strategies to avoid deadlock:
Practical case: The dining philosophers problem
The dining philosophers problem is a classic deadlock problem. There are 5 philosophers sitting around a round table, each with a chopstick. They can eat with two chopsticks on the left and right at any time, but they can only take one chopstick at the same time. If all philosophers pick up the left chopstick at the same time, they will all be in a deadlock.
We can use the Orderly use of resources strategy to solve this problem:
// 筷子类 class Chopstick { public: Chopstick() { m_mutex = new std::mutex; } ~Chopstick() { delete m_mutex; } void lock() { m_mutex->lock(); } void unlock() { m_mutex->unlock(); } private: std::mutex* m_mutex; }; // 哲学家类 class Philosopher { public: Philosopher(int id, Chopstick* left, Chopstick* right) : m_id(id), m_left(left), m_right(right) {} void dine() { while (true) { // 获取左边的筷子 m_left->lock(); // 获取右边的筷子 m_right->lock(); // 进餐 std::cout << "哲学家 " << m_id << " 正在进餐" << std::endl; // 放下右边的筷子 m_right->unlock(); // 放下左边的筷子 m_left->unlock(); } } private: int m_id; Chopstick* m_left; Chopstick* m_right; }; int main() { // 创建 5 根筷子 Chopstick chopsticks[5]; // 创建 5 个哲学家 Philosopher philosophers[5] = { Philosopher(0, &chopsticks[0], &chopsticks[4]), Philosopher(1, &chopsticks[1], &chopsticks[0]), Philosopher(2, &chopsticks[2], &chopsticks[1]), Philosopher(3, &chopsticks[3], &chopsticks[2]), Philosopher(4, &chopsticks[4], &chopsticks[3]) }; // 启动哲学家线程 std::thread threads[5]; for (int i = 0; i < 5; i++) { threads[i] = std::thread(&Philosopher::dine, &philosophers[i]); } // 等待哲学家线程结束 for (int i = 0; i < 5; i++) { threads[i].join(); } return 0; }
In this example, we create a std for each chopstick: :mutex
Mutex lock, ensuring that only one philosopher can obtain the chopsticks at a time. By getting the chopsticks in order, we avoid deadlock.
The above is the detailed content of Deadlock in C++ concurrent programming and strategies to avoid deadlock?. For more information, please follow other related articles on the PHP Chinese website!