MyClass
has a member function that needs to return its' member variable, and
the function must be thread safe, so I use a mutex to protect the data.
I have two implementation as below:
version 1:
string MyClass::name() {
m_mutex.lock();
string temp = m_name;
m_mutex.unlock();
return temp;
}
version 2:
string MyClass::name() {
MutexLocker lock(mutex);
return m_name;
}
I known that version 1 has no problem, but I need to type more code.
The problem is, I'm not sure whether version 2 is correct or not. Will the mutex lock will be released before the thread access m_name
?
The version 2 is correct as well (in fact, that is better than the first version!).
The value is copied first before mutex is released through the destructor of the local object. The opposite is not possible because the local object gets destroyed when it goes out of scope, but you must note that the return statement must be executed in the scope, so it must happen before destruction. Conversely, the return statement cannot be executed after the local object goes out of scope.
From call-stack point of view, the local objects are destroyed when the stack starts unwinding, but the function including the return statement is executed long before stack-unwinding. That ensures m_name
is copied much before the releasing the mutex.
Or think of this simple code:
std::string f()
{
std::string s = "Nawaz";
return s; //Think of this line!
}
Is s
copied1after its destruction? Is that even possible? Wouldn't it make programming in C++ impossible if s
is copied after its destruction?
1. Or better say, moved. :-)
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