【发布时间】:2011-01-17 12:53:31
【问题描述】:
所以有这样的课程:
class mySafeData
{
public:
mySafeData() : myData(0), changed( false )
{
}
void Set(int i)
{
boost::mutex::scoped_lock lock(myMutex);
myData = i; // set the data
changed = true; // mark as changed
myCondvar.notify_one(); // notify so a reader can process it
}
void Get( int& i)
{
boost::mutex::scoped_lock lock(myMutex);
while( !changed )
{
myCondvar.wait( lock );
}
i = myData;
changed = false; // mark as read
myCondvar.notify_one(); // notify so the writer can write if necessary
}
private:
int myData;
boost::mutex myMutex;
boost::condition_variable myCondvar;
bool changed;
};
循环中的一个线程调用Set。以及 3 个或更多线程调用 Get 如何使所有线程调用 Get 以实际获取数据(每个线程应仅在调用 Set 时 Get 数据)(似乎只有第一个调用的“读者” Get 获取数据)?
更新会这样吗?:
class mySafeData
{
public:
mySafeData() : myData(0)
{
}
void Set(int i)
{
boost::mutex::scoped_lock lock(myMutex);
myData = i; // set the data
}
void Get( int& i)
{
boost::mutex::scoped_lock lock(myMutex);
i = myData;
}
private:
int myData;
boost::mutex myMutex;
};
【问题讨论】:
标签: c++ multithreading oop boost locking