Qt,QMutex 如何工作?好像没用

Mr.*_*.Tu 1 qt

我的代码如下:

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;
}
Run Code Online (Sandbox Code Playgroud)

>

class MyThread : public QThread
{
    Q_OBJECT
public:
    explicit MyThread(QObject *parent = 0);
    void run();
};
Run Code Online (Sandbox Code Playgroud)

>

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();
}
Run Code Online (Sandbox Code Playgroud)

但结果是:

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
...
...
Run Code Online (Sandbox Code Playgroud)

我想要的结果是:

xxx:10000
xxx:9999
xxx:9998
xxx:9997
...
...
xxx: 1

年:10000
年:9999
...
...  
年:1

为什么?我的错在哪里?以及如何使用QMutex..谢谢...

Kim*_*meh 5

您正在 run 调用的范围内创建互斥体。如果您希望互斥体停止/延迟线程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
}
Run Code Online (Sandbox Code Playgroud)