So I have a datastructure which ensures thread safety using a rwlock. And I have a RAII ScopedRWLock which locks when created and unlocks when destructor. So for an accessor function, I have:
int GetValue() const
{
ScopedRWLock(&m_rwlock);
return m_value;
}
Now this doesn't work as compiler complains about having the ScopedRWLock with const. I tried replacing ScopedRWLock with just plain read lock and read unlock and doesn't work either. So question is how do people achieve regular (not lock-free) thread safety while still achieving const-correctness??
Thanks
You create the scoped lock but then immediately destroy it, so it fails to protect your access to m_value
. You wanted this:
int GetValue() const
{
ScopedRWLock l(&m_rwlock);
return m_value;
}
Now, the lock remains in scope until m_value
is accessed.
Your probably also want to declare the lock mutable
so it can be accessed in const
member functions.