C++ 增强互斥顺序
所以有简单的课程C++ 增强互斥顺序,c++,multithreading,boost,locking,C++,Multithreading,Boost,Locking,所以有简单的课程 class mySafeData { public: mySafeData() : myData(0) { } void Set(int i) { boost::mutex::scoped_lock lock(myMutex); myData = i; // set the data ++stateCounter; // some int to track state chages myCondvar.notify_all(
class mySafeData
{
public:
mySafeData() : myData(0)
{
}
void Set(int i)
{
boost::mutex::scoped_lock lock(myMutex);
myData = i; // set the data
++stateCounter; // some int to track state chages
myCondvar.notify_all(); // notify all readers
}
void Get( int& i)
{
boost::mutex::scoped_lock lock(myMutex);
// copy the current state
int cState = stateCounter;
// waits for a notification and change of state
while (stateCounter == cState)
myCondvar.wait( lock );
}
private:
int myData;
int stateCounter;
boost::mutex myMutex;
};
无限循环中的线程数组调用每个函数
Get()
Set()
Get()
Get()
Get()
他们是否总是以相同的顺序调用函数,并且每个循环只调用一次(我的意思是,每次都会以相同的顺序运行所有的boost线程,这样每个线程在一次
设置()之后只会获取())一次?否。你永远不能假设线程的服务顺序。这与boost无关,它是多道程序设计的基础。不。你永远不能假设线程的服务顺序。这与boost无关,它是多道程序设计的基础。线程应该以到达作用域锁的相同顺序获得锁(我认为)。但不能保证他们会以任何固定的顺序到达那个点
所以一般来说:不要依赖它。线程应该以到达作用域锁的相同顺序获得锁(我认为)。但不能保证他们会以任何固定的顺序到达那个点
所以一般来说:不要依赖它。不,互斥锁只会阻止两个线程同时访问变量。它不会影响线程的调度顺序或执行时间,因为无论出于何种目的,都可以假定线程调度顺序或执行时间是随机的。否,互斥锁只会阻止两个线程同时访问变量。它不会影响线程的调度顺序或执行时间,因为无论出于何种目的,都可以假定线程的调度顺序或执行时间是随机的