Last updated:2026-10-12
Helgrind Concurrency Error Detection¶
helgrind concurrency checking from C++那些事¶
Usually, when we write multi-threaded programs, we easily run into two problems:
- A deadlock happened and we do not know what caused it
- Data inconsistency caused by multiple threads using locks incorrectly
So is there a tool that can detect these two scenarios?
The answer is yes: we can use valgrind's helgrind tool to detect these two problems. To make this article flow more smoothly, a few examples are introduced.
Note: the complete examples and the fixed examples have been published in the Knowledge Planet.
Deadlock¶
Suppose two threads each hold the other's lock; we can simulate a deadlock like this:
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 is used as follows:
At this point we can see where the deadlock is; for example, this output points out the two threads deadlocking at the corresponding locations

Data race¶
Suppose there is a shared variable that we increment 100,000 times from multiple threads — what will the result be?
Clearly there is a problem here of multiple threads racing on a global variable, and the final result is inconsistent; use the same helgrind detection method as above.
At this point, we can see on which line the data race occurs, and then go fix the problem.

Finally, here are a few questions to leave you with:
1.How do you fix the two pieces of problematic code above?
2.Besides the tools above, are there any other approaches?
End of this section
Related Topics¶
- C++ Concurrency in Action Reading Guide | C++那些事
- C++ Deadlock Troubleshooting | C++那些事
- C++ SIMD Vectorization | C++那些事
- C++17 Parallel STL | C++那些事
- C++ False Sharing and Cache Lines | C++那些事
- GDB Multi-Threaded All-Stop Debugging | C++那些事
- libev Event Loop Internals | C++那些事
- C++ std::thread Implementation Internals | C++那些事
- C++ std::thread and jthread | C++那些事
- Getting Started with C++ Multithreading | C++那些事