MyClass has a member function that should return its member variable, and the function should be thread safe, so I use a mutex to protect the data.
MyClass
I have two implementations as shown 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 knew that version 1 had no problems, but I needed to enter more code.
The problem is that I'm not sure if version 2 is correct or not. Will a mutex lock be released before thread access m_name?
m_name
Version 2 is also correct (in fact, it is better than the first version!).
, mutex . , , , , return , . , return .
-, , , , return, . , m_name .
:
std::string f() { std::string s = "Nawaz"; return s; //Think of this line! }
s 1 ? ? ++ , s ?
s
1. , .: -)