我有一個C++ 11線程死鎖。這是通過使用具有多個線程池的兩個獨立函數來實現的。爲了避免這種僵局,這個例子如何解決?我認爲解決方案與鎖定程序的一致排序有關。如何修復一個C++線程死鎖的例子
#include <thread>
#include <mutex>
#include <iostream>
std::mutex kettle;
std::mutex tap;
#define THREAD_POOL 8
void kettle_tap(){
std::cout << "Locking kettle in " << std::this_thread::get_id() << std::endl;
// Lock the mutex kettle by creating and using lock_guard kettle_lock.
std::lock_guard<std::mutex> kettle_lock(kettle);
std::cout << "Locked kettle in " << std::this_thread::get_id() << std::endl;
std::cout << "Locking tap in " << std::this_thread::get_id() << std::endl;
// Lock the mutex tap by creating and using lock_guard tap_lock.
std::lock_guard<std::mutex> tap_lock(tap);
std::cout << "Locked tap in " << std::this_thread::get_id() << std::endl;
std::cout << "Filling kettle in " << std::this_thread::get_id() << std::endl;
}
void tap_kettle(){
std::cout << "Locking tap in " << std::this_thread::get_id() << std::endl;
// Lock the mutex tap by creating and using lock_guard tap_lock.
std::lock_guard<std::mutex> tap_lock(tap);
std::cout << "Locked tap in " << std::this_thread::get_id() << std::endl;
std::cout << "Locking kettle in " << std::this_thread::get_id() << std::endl;
// Lock the mutex kettle by creating and using lock_guard kettle_lock.
std::lock_guard<std::mutex> kettle_lock(kettle);
std::cout << "Locked kettle in " << std::this_thread::get_id() << std::endl;
std::cout << "Filling kettle in " << std::this_thread::get_id() << std::endl;
}
int main(){
std::thread pool[THREAD_POOL];
for (int t = 0; t < THREAD_POOL; t += 2){
pool[t] = std::thread(kettle_tap);
pool[t+1] = std::thread(tap_kettle);
}
for (int t = 0; t < THREAD_POOL; ++t){
pool[t].join();
}
std::cout << "Threads are all joined" << std::endl;
return 0;
}
啊,非常好。感謝您的幫助和所有的細節。鎖定採用技巧很好。 – d3pd 2014-09-04 09:06:09