C++ 多线程的错误和如何避免(6)
加锁的临界区要尽可能的紧凑和小型
问题分析:
当一个线程在临界区内执行时,所有其他试图进入临界区的线程都会被阻止,所以我们应该保证临界区尽可能的小。比如,
void CallHome(string message) { std::lock_guard<std::mutex> lock(mu); // Start of Critical Section - to protect std::cout ReadFifyThousandRecords(); cout << "Thread " << this_thread::get_id() << " says " << message << endl; }// lock_guard object is destroyed and mutex mu is released
ReadFifyThousandRecords() 方法是一个只读操作,没有任何理由让它在锁内执行,如果它需要花费 10s 从一个 DB
中读取五万次记录的话,那所有其他的线程会被这段并不需要的时间给阻塞。它将严重影响程序的执行效率。
正确的方式应该是只把 std::cout 放进临界区内,比如,
void CallHome(string message) { ReadFifyThousandRecords(); // Don't need to be in critical section because it's a read only operation std::lock_guard<std::mutex> lock(mu); // Start of Critical Section - to protect std::cout cout << "Thread " << this_thread::get_id() << " says " << message << endl; }// lock_guard object is destroyed and mutex mu is released