QMutex与QThread - 分段故障

aha*_*mas 1 c++ qt qthread qmutex

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

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

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

当我调用pause()方法时MyClass,我得到Segmentation故障信号指向(在调试模式下)到MyThread.cpp中的第3行 - syncMutex.lock();.它不依赖于MyThread实例的数量- 它甚至在std :: vector中的1个线程中断.

我很确定我错过了一些重要的东西,但我不知道是什么.我究竟做错了什么?

(如果确实重要,我使用QG 5的MinGW 4.7编译器)

小智 5

在for循环中使用this->threadsVector.size()而不是sizeof(this->threadsVector)找出向量包含的项目数.