Qt,QMutex如何运作?它似乎没有用

时间:2012-02-06 10:27:48

标签: 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;
}

>

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 ..谢谢......

3 个答案:

答案 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)

您可以查看开发人员的解释here

这是一个很好的无锁编程,很难重新实现,甚至更难以调试和验证。

然而,它指向Linux futexesQMutex在Linux平台上使用 如果可移植性不是问题,您可能想要使用它。

这回答了你的问题标签。

但是,在您的特定情况下,您并不真的需要它。只需创建一个由所有工作线程共享的全局互斥锁即可。