c++multithreadingc++11clang

Clang thread safety analysis with C++ standard library


This describes how static thread safety analysis can be done with annotations in C++: http://clang.llvm.org/docs/ThreadSafetyAnalysis.html

How can I use this with standard types like std::mutex and std::lock_guard?

The example code of mutex.h annotates a custom interface. Do I have the type "Mutex" which is defined there and implement a class using std::mutex with the annotated methods or does Clang bring annotated types somehow?


Solution

  • In recent versions of clang, you probably don't have to wrap std::mutex anymore, because the thread-safety annotations are included since March 15, 2016.

    This adds clang thread safety annotations to std::mutex and std::lock_guard so code using these types can use these types directly instead of having to wrap the types to provide annotations. These checks when enabled by -Wthread-safety provide simple but useful static checking to detect potential race conditions.

    See http://clang.llvm.org/docs/ThreadSafetyAnalysis.html for details.

    So simply having -Wthread-safety should be enough.