Is std::mutex as a member variable thread-safe for multiple threads?
There is an instance of a class has a variable and mutex as a member.
Each function is called in different threads.
I am curious that is it okay to use a mutex like this?
There are lots of example codes using a kind of wrapper class for mutex like guard or something.
I prefer to use it simply and want to unlock explicitly. Not in destructing time.
#include <mutex>
#include <stdio.h>
class A {
private:
bool _is;
std::mutex _mutex;
}
// this function runs in Thread A
void A::read() {
_mutex.lock();
printf("%d", _is);
_mutex.unlock();
}
// this function runs in Thread B
void A::write() {
_mutex.lock();
printf("%d", _is);
_is = !_is;
_mutex.unlock();
}