I am trying to get thread synchronization to work.
Below is a sample code (Runnable C++ shell example) for illustration.
When I run the program, the three member functions bar1()
, bar2()
and bar3()
are executed.
My aim though is to use one thread for each of these functions.
I have access to the boost library in my development environment.
I know how to use threads and have also implemented a ThreadedProcess()
function below. But it's not thread safe as I understand because multiple threads might want to access the same memory at the same time.
So my question is, how would I ensure that the members can only be accessed by one thread at a time.
Thank you!
#include <iostream>
#include <string>
struct TestStruct {
int nVal;
double dVal;
TestStruct(){}
TestStruct(int n, double d) : nVal(n), dVal(d)
{
}
};
class Foo{
public:
Foo() :m_oO1(58, 17.3), m_oO2(11, 20.8), m_oO3(7, 56.3) {}
~Foo(){}
void Process()
{
bar1();
bar2();
bar3();
}
void ThreadedProcess()
{
m_oThread1 = boost::thread(boost::bind(&Foo::bar1, this));
m_oThread2 = boost::thread(boost::bind(&Foo::bar2, this));
m_oThread3 = boost::thread(boost::bind(&Foo::bar3, this));
}
protected:
TestStruct m_oO1;
TestStruct m_oO2;
TestStruct m_oO3;
TestStruct m_oO4;
boost::thread m_oThread1;
boost::thread m_oThread2;
boost::thread m_oThread3;
int bar1()
{
int nRet = m_oO1.nVal * m_oO2.nVal;
std::cout << nRet << std::endl;
return nRet;
}
double bar2()
{
double dRet = m_oO2.dVal + m_oO3.dVal;
std::cout << dRet << std::endl;
return dRet;
}
double bar3()
{
double dRet = m_oO2.dVal * m_oO3.dVal * m_oO3.dVal;
std::cout << dRet << std::endl;
return dRet;
}
};
int main(int /*argc*/, char** /*argv*/)
{
Foo myFoo;
myFoo.Process();
myFoo.ThreadedProcess();
}