문제

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 read_lock(&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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top