提高互斥锁顺序 [英] Boost mutex order
本文介绍了提高互斥锁顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以上课简单
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;
};
和无限循环中的线程数组调用每个函数
and array of threads in infinite loops calling each one function
Get()
Set()
Get()
Get()
Get()
它们将始终以相同的顺序调用函数,并且每个循环仅调用一次(按圆圈,我的意思是所有升压线程每次都将以相同的顺序运行,因此每个线程在一个Set
( ))?
will they always call functions in the same order and only once per circle (by circle I mean will all boost threads run in same order each time so that each thread would Get
() only once after one Set
())?
推荐答案
线程应该以到达scoped_lock
构造函数的顺序来获取锁(我认为).但是并不能保证他们会以任何固定顺序到达这一点!
The threads should acquire the lock in the same order that they reach the scoped_lock
constructor (I think). But there's no guarantee that they will reach that point in any fixed order!
因此,一般来说:不要依赖它.
So in general: don't rely on it.
这篇关于提高互斥锁顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文