use*_*869 4 c++ qt mutex recursive-mutex
我正在尝试使用递归QMutex,我读了QMutex类参考,但我不明白该怎么做,有人可以举个例子吗?我需要一些方法来锁定QMutex,可以在调用lock方法之后或之前解锁.如果递归互斥不是这样的方式还有其他方法吗?
要创建递归QMutex,只需QMutex::Recursive在构造时传递,例如:
QMutex mutex(QMutex::Recursive);
int number = 6;
void method1()
{
mutex.lock();
number *= 5;
mutex.unlock();
}
void method2()
{
mutex.lock();
number *= 3;
mutex.unlock();
}
Run Code Online (Sandbox Code Playgroud)
Recursive意味着你可以从同一个线程锁定多次互斥锁,你不必解锁它.如果我理解你的问题就是你想要的.
要小心,如果你递归锁定,你必须调用解锁相同的次数.锁定/解锁互斥锁的更好方法是使用aQMutexLocker
#include <QMutexLocker>
QMutex mutex(QMutex::Recursive);
int number = 6;
void method1()
{
QMutexLocker locker(&mutex); // Here mutex is locked
number *= 5;
// Here locker goes out of scope.
// When locker is destroyed automatically unlocks mutex
}
void method2()
{
QMutexLocker locker(&mutex);
number *= 3;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5496 次 |
| 最近记录: |