Consider the following C++ member function:
size_t size() const
{
boost::lock_guard<boost::mutex> lock(m_mutex);
return m_size;
}
The intent here is not to synchronize access to the private member variable m_size
, but just to make sure that the caller receives a valid value for m_size. The goal is to prevent the function from returning m_size
at the same time that some other thread is modifying m_size
.
But is there any potential race-condition involved in calling this function? I'm not sure if the RAII style lock here is adequate to protect against a race condition. Suppose the lock's destructor is called before the return value of the function is pushed onto the stack?
Would I need to do something like the following to guarantee thread-safety?
size_t size() const
{
size_t ret;
{
boost::lock_guard<boost::mutex> lock(m_mutex);
ret = m_size;
}
return ret;
}