Reputation: 1332
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?
Upvotes: 9
Views: 4761
Reputation: 4131
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.
Upvotes: 3
Reputation: 3801
Implement the interface described in the supplied mutex.h file, and use the std::mutex class to do so. I.e here is a half-finished implementation:
Minor change to mutex.h file to include a std::mutex object
class CAPABILITY("mutex") Mutex {
private:
std::mutex std_mutex;
public:
// Acquire/lock this mutex exclusively. Only one thread can have exclusive
// access at any one time. Write operations to guarded data require an
// exclusive lock.
Then implement the rest in mutex.cpp
#include "mutex.h"
void Mutex::Lock(){
this->std_mutex.lock();
}
void Mutex::Unlock(){
this->std_mutex.unlock();
}
bool Mutex::TryLock(){
return this->std_mutex.try_lock();
}
Upvotes: 2