In C++ multi-threaded programming, the main causes of deadlock are: 1. Improper use of mutex locks; 2. Sequential locking. In actual combat, if multiple threads try to acquire the same set of locks at the same time and acquire them in different orders, deadlock may occur. This can be avoided by always acquiring locks in the same order.
Causes of deadlock in C++ multi-threaded programming
Deadlock is a common error in concurrent programming. Occurs when one or more threads are waiting for another thread to release the lock, and the other thread is waiting for the former to release the lock. This will cause the program to become stuck and unable to continue execution.
In C++, deadlocks are usually caused by the following reasons:
Practical case:
Consider the following code:
class BankAccount { public: std::mutex m_mutex; // 互斥锁 int balance = 0; }; void transfer(BankAccount &from, BankAccount &to, int amount) { std::lock_guard<std::mutex> lock1(from.m_mutex); // 锁定第一个账户 std::lock_guard<std::mutex> lock2(to.m_mutex); // 锁定第二个账户 // 从第一个账户扣除金额 from.balance -= amount; // 将金额添加到第二个账户 to.balance += amount; }
In this example, if two threads call transfer at the same time ()
function and they try to transfer money from different accounts to the same account, a deadlock occurs. This is because one thread will first lock the first account and then wait for another thread to release the second account, and the other thread will first lock the second account and then wait for the first thread to release the first account.
To avoid this, threads should always acquire locks in the same order, for example:
void transfer(BankAccount &from, BankAccount &to, int amount) { // 按照账户 ID 排序账户 if (from.getId() < to.getId()) { std::lock_guard<std::mutex> lock1(from.m_mutex); std::lock_guard<std::mutex> lock2(to.m_mutex); } else { std::lock_guard<std::mutex> lock2(to.m_mutex); std::lock_guard<std::mutex> lock1(from.m_mutex); } // 从第一个账户扣除金额 from.balance -= amount; // 将金额添加到第二个账户 to.balance += amount; }
By sorting accounts by account ID and locking them in the same order, we can prevent this situation occurs.
The above is the detailed content of What are the causes of deadlocks in C++ multi-threaded programming?. For more information, please follow other related articles on the PHP Chinese website!