我最近实现线程/互斥锁管理器的努力最终导致 75% 的 CPU 负载(4 核),而所有四个正在运行的线程要么处于睡眠状态,要么等待互斥锁解锁。
特定的类太大了,无法在这里完全发布,但我可以将原因缩小到死锁安全地获取两个互斥锁
std::unique_lock<std::mutex> lock1( mutex1, std::defer_lock );
std::unique_lock<std::mutex> lock2( mutex2, std::defer_lock );
std::lock( lock1, lock2 );
该类的另一部分使用std::condition_variable
withwait()
和notify_one()
onmutex1
来同时有选择地执行某些代码。
简单的改变
std::unique_lock<std::mutex> lock1( mutex1 );
std::unique_lock<std::mutex> lock2( mutex2 );
将 CPU 使用率降至正常的 1-2%。
我不敢相信,这个std::lock()
功能是那么低效。这可能是 g++ 4.6.3 中的错误吗?
编辑:(示例)
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
std::mutex mutex1, mutex2;
std::condition_variable cond_var;
bool cond = false;
std::atomic<bool>done{false};
using namespace std::chrono_literals;
void Take_Locks()
{
while( !done )
{
std::this_thread::sleep_for( 1s );
std::unique_lock<std::mutex> lock1( mutex1, std::defer_lock );
std::unique_lock<std::mutex> lock2( mutex2, std::defer_lock );
std::lock( lock1, lock2 );
std::this_thread::sleep_for( 1s );
lock1.unlock();
lock2.unlock();
}
}
void Conditional_Code()
{
std::unique_lock<std::mutex> lock1( mutex1, std::defer_lock );
std::unique_lock<std::mutex> lock2( mutex2, std::defer_lock );
std::lock( lock1, lock2 );
std::cout << "t4: waiting \n";
while( !cond )
cond_var.wait( lock1 );
std::cout << "t4: condition met \n";
}
int main()
{
std::thread t1( Take_Locks ), t2( Take_Locks ), t3( Take_Locks );
std::thread t4( Conditional_Code );
std::cout << "threads started \n";
std::this_thread::sleep_for( 10s );
std::unique_lock<std::mutex> lock1( mutex1 );
std::cout << "mutex1 locked \n" ;
std::this_thread::sleep_for( 5s );
std::cout << "setting condition/notify \n";
cond = true;
cond_var.notify_one();
std::this_thread::sleep_for( 5s );
lock1.unlock();
std::cout << "mutex1 unlocked \n";
std::this_thread::sleep_for( 6s );
done = true;
t4.join(); t3.join(); t2.join(); t1.join();
}