I have the following mutex classes (hopefully) implemented after the clang thread safety model. (http://clang.llvm.org/docs/ThreadSafetyAnalysis.html)
class CAPABILITY( "mutex" ) Mutex : public std::mutex
{
public:
void lock() ACQUIRE()
{
std::mutex::lock();
}
void unlock() RELEASE()
{
std::mutex::unlock();
}
};
class SCOPED_CAPABILITY LockGuard : public std::unique_lock< std::mutex >
{
public:
LockGuard( Mutex& mu ) ACQUIRE( mu ) : std::unique_lock< std::mutex >( mu )
{
}
~LockGuard() RELEASE()
{
}
};
The usage is as follows:
class Barrier
{
...
Mutex mutex_;
std::condition_variable cv_ GUARDED_BY( mutex_ );
std::size_t min_count_ GUARDED_BY( mutex_ );
std::size_t count_ GUARDED_BY( mutex_ );
bool Barrier::waitFor( const std::chrono::microseconds& duration )
{
LockGuard lock( mutex_ );
if ( count_ >= min_count_ )
{
return true;
}
else
{
// WARNING IS IN THE LINE BELOW
return cv_.wait_for( lock, duration, [this]() { return count_ >= min_count_; } );
}
}
};
I get the clang warning:
warning: reading variable 'count_' requires holding mutex 'mutex_' [-Wthread-safety-analysis]
.
Is the warning of the compiler (clang 3.8 with -Wthread-safety) correct? If yes, how exactly does the violation happen?
Because it is not clear to the compiler, where the lambda expression is evaluated, it is necessary to annotate the lambda as well.
The correct line, which doesn't yield any error is
return cv_.wait_for( lock, duration, [this]() REQUIRES( mutex_ ) { return count_ >= min_count_; } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With