【问题标题】:QMutex with QThread - Segmentation faultQMutex 与 QThread - 分段错误
【发布时间】:2013-05-17 15:22:26
【问题描述】:

我有一个 C++ Qt 程序,它使用 QThread 和使用 QMutex 和 QWaitCondition 实现的暂停/恢复机制。看起来是这样的:

MyThread.h:

class MyThread : public QThread
{
    Q_OBJECT

    public:
        MyThread();
        void pauseThread();
        void resumeThread();

    private:
        void run();
        QMutex syncMutex;
        QWaitCondition pauseCond;
        bool pause = false;
}

MyThread.cpp:

void MyThread::pauseThread()
{
    syncMutex.lock();
    pause = true;
    syncMutex.unlock();
}

void MyThread::resumeThread()
{
    syncMutex.lock();
    pause = false;
    syncMutex.unlock();
    pauseCond.wakeAll();
}

void MyThread::run()
{
    for ( int x = 0; x < 1000; ++x )
    {
        syncMutex.lock();
        if ( pause == true )
        {
            pauseCond.wait ( &syncMutex );
        }
        syncMutex.unlock();
        //do some work
    }
}

我使用 MyThread 类的向量:

void MyClass::createThreads()
{
    for ( int x = 0; x < 2; ++x)
    {
        MyThread *thread = new MyThread();
        thread->start();

        //"std::vector<MyThread *> threadsVector" is defined in header file
        this->threadsVector.push_back ( thread ); 
    }
}

void MyClass::pause()
{
    for ( uint x = 0; x < sizeof ( this->threadsVector ); ++x )
    {
        this->threadsVector[x]->pauseThread();
    }
}

void MyClass::resume()
{
    for ( uint x = 0; x < sizeof ( this->threadsVector ); ++x )
    {
        this->threadsVector[x]->resumeThread();
    }
}

当我调用 MyClasspause() 方法时,我得到分段错误信号(在调试模式下)指向 MyThread.cpp - syncMutex.lock(); 中的第 3 行。它不依赖于 MyThread 实例的数量 - 它甚至可以在 std::vector 中使用 1 个线程。

我很确定我错过了一些重要的事情,但我不知道是什么。我做错了什么?

(如果重要的话,我使用带有 Qt 5 的 MinGW 4.7 编译器)

【问题讨论】:

  • 我还建议使用 QAtomicBool 而不是用与等待条件相同的互斥锁来保护布尔值。

标签: c++ qt qthread qmutex


【解决方案1】:

在 for 循环中,使用 this-&gt;threadsVector.size() 而不是 sizeof(this-&gt;threadsVector) 来找出向​​量包含多少项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-21
    • 2010-10-24
    • 2011-10-20
    • 1970-01-01
    • 2020-12-15
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多