Skip to content

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:

valgrind --tool=helgrind ./a.out 

At this point we can see where the deadlock is; for example, this output points out the two threads deadlocking at the corresponding locations

thread_func2() (deadlock.cc:18)
thread_func1() (deadlock.cc:12)

deadlock

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.

int shared_var = 0; 

void increment() {
    for (int i = 0; i < 100000; ++i) {
        ++shared_var; 
    }
}

At this point, we can see on which line the data race occurs, and then go fix the problem.

datarace

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

Comments