我正在尝试让线程同步工作。下面是一个示例代码(可运行的C++ shell 示例)用于说明。当我运行程序时,三个成员函数bar1()
,bar2()
和bar3()
被执行。不过,我的目标是为这些功能中的每一个使用一个线程。我可以在我的开发环境中访问 boost 库。我知道如何使用线程并且还在ThreadedProcess()
下面实现了一个功能。但据我所知,它不是线程安全的,因为多个线程可能想要同时访问同一个内存。所以我的问题是,我如何确保成员一次只能被一个线程访问。谢谢!
#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();
}