C++那些事之helgrind并发编程检测
大纲
死锁
数据竞争
提问
通常我们在写多线程程序的时候很容易遇到两个问题:
死锁了,不知道什么原因导致
数据不一致,多个线程没保护数据
那么有没有工具来检测这两种场景呢
答案是有的,我们可以使用valgrind的helgrind工具检测这两个问题,为了使本文讲解的更加丝滑,引出了几个例子。
注:完整示例及修复示例已更新至星球。
死锁
假设有两个线程互相持有对方的锁,此时我们可以模拟出死锁,例如:
void thread_func1() {
std::lock_guard<std::mutex> lock1(mutex1);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::lock_guard<std::mutex> lock2(mutex2);
}
void thread_func2() {
std::lock_guard<std::mutex> lock2(mutex2);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::lock_guard<std::mutex> lock1(mutex1);
}
helgrind使用的方法如下:
<