Reputation: 65
Here is an excellent piece of code that addresses how to use a lock on member functions of an object.
#include <thread>
#include <mutex>
#include <iostream>
class Foo
{
public:
void increment()
{
for ( int i = 0; i < 10000000; ++i )
{
std::lock_guard<std::mutex> lock(mtx); //lock mtx
++x;
// mtx is automatically released when lock
// goes out of scope -> RAII
}
}
void decrement()
{
for ( int i = 0; i < 10000000; ++i )
{
std::lock_guard<std::mutex> lock(mtx); //lock mtx
--x;
// mtx is automatically released when lock
// goes out of scope -> RAII
}
}
static int x;
static std::mutex mtx;
};
int Foo::x = 0;
std::mutex Foo::mtx;
int main()
{
std::thread t1(&Foo::increment, Foo());
std::thread t2(&Foo::decrement, Foo());
t1.join();
t2.join();
std::cout << Foo::x;
}
My question is, how to implement this if the constructor has a data member initialization list. Is it possible?
Upvotes: 0
Views: 589
Reputation: 6427
You don't need an additional lock if Foo
has data member initialization list as each thread has it's own instance of Foo
class. Member initialization list specifies the initializers for direct and virtual base subobjects and non-static data members.
You only need a lock
to control the consistence of state shared between threads. Like static Foo::x
in your sample.
Upvotes: 1