Reputation: 61
#include <iostream>
#include <mutex>
using namespace std;
class TestClass {
public : // members
std::mutex m_mutex;
int m_var;
public : //functions
TestClass()
:m_var(0) {};
void fooIncVar()
{
cout << "calling inc var" << endl;
std::scoped_lock lock(m_mutex);
_incVar();
}
private:
void _incVar()
{
std::scoped_lock lock(m_mutex);
m_var++;
cout << "var : " << m_var << endl;
}
};
int main()
{
cout<<"Hello World" << endl;
auto a = A();
a.fooIncVar();
return 0;
}
I am trying to understand how scoped_lock works with a mutex. I was expecting that below program will just hang because I am calling _incVar
by holding the mutex in fooIncVar
since scope of the variable is until the end of the function. But that doesn't seem to be the case. I get the following output
Hello World
calling inc var
var : 1
Upvotes: 0
Views: 364