C++ 多线程的错误和如何避免(4)
对共享的资源或者数据做加锁处理
在多线程的环境下,有时需要多个线程对同一个资源或者数据进行操作,如果没有加锁,容易出现未定义的行为。
比如:
#include#include #include #include using namespace std; std::mutex mu; void CallHome(string message) { cout << "Thread " << this_thread::get_id() << " says " << message << endl; } int main() { thread t1(CallHome, "Hello from Jupiter"); thread t2(CallHome, "Hello from Pluto"); thread t3(CallHome, "Hello from Moon"); CallHome("Hello from Main/Earth"); thread t4(CallHome, "Hello from Uranus"); thread t5(CallHome, "Hello from Neptune"); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); return 0; }
编译后:
我们会发现 thread id 为 13984 的线程在输出到一半时被另一个线程输出的文本截断了,如果避免这种行为呢,我们需要给线程函数的 std:: cout 加一个锁。
这样就可以保证同一时间只有一个线程被允许调用 std::cout
修改:
void CallHome(string message)
{
mu.lock();
cout << "Thread " << this_thread::get_id() << " says " << message << endl;
mu.unlock();
}
输出: