我的代码如下:
int main(int argc, char* argv[])
{
MyThread myThread1;
MyThread myThread2;
myThread1.start();
myThread2.start();
qDebug("Hello World");
myThread1.wait();
qDebug("myThread1 is finished...");
myThread2.wait();
qDebug("myThread2 is finished...");
return 0;
}
>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = 0);
void run();
};
>
void MyThread::run()
{
QMutex mutex();
int x = 10000;
mutex.lock();
while(x != 0) {
sleep(1);
qDebug("%d, x = %d ", thread()->currentThreadId(), x);
x--;
}
mutex.unlock();
}
但结果是:
Hello World
5516, x = 10000
6060, x = 10000
5516, x = 9999
6060, x = 9999
5516, x = 9998
6060, x = 9998
5516, x = 9997
6060, x = 9997
...
...
我想结果是:
xxxx: 10000 xxxx: 9999 xxxx: 9998 xxxx: 9997 ... ... xxxx: 1 yyyy: 10000 yyyy: 9999 ... ... yyyy: 1
为什么呢?我的错在哪里?以及如何使用QMutex ..谢谢......
答案 0 :(得分:4)
您正在运行调用范围内创建互斥锁。如果您希望互斥锁停止/延迟线程2的执行,则需要声明,以便您的对象不会每次都创建自己的互斥锁。
// .h
class MyThread {
...
private:
static QMutex mutex;
}
// .cpp
QMutex MyThread::mutex;
// .cpp
void MyThread::run()
{
QMutexLocker lock(&mutex)
// do stuff then return
// and the mutex will be unlocked when
// you leave this scope
}
答案 1 :(得分:2)
您的互斥对象是本地对象。因此,线程使用不同的互斥锁,而锁定的互斥锁不会影响另一个。
要修复它,请将QMutex
对象移动到两个线程都可以访问它的位置。例如,将其设为全局变量。
此外,在函数中使用RAII风格QMutexLocker
更容易,而不是明确调用lock()
和unlock()
。
答案 2 :(得分:0)