c++ - QMutex 与 QThread - 段错误

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

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 类的 vector :

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() 方法时,我得到 Segmentation fault signal pointing (in Debug mode) to line 3 in MyThread.cpp - syncMutex .lock();。它不依赖于 MyThread 实例的数量 - 它甚至在 std::vector 中有 1 个线程。

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

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

最佳答案

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

关于c++ - QMutex 与 QThread - 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16612662/

相关文章:

c++ - 点容器

c++ - 未在范围内声明 - priority_queue C++ 的友元比较器类

QT - QGridLayout 需要不同的标题行间距

python - 正确使用 QThread.currentThreadId()

c++ - 在浮点精度成为问题之前可以将多少个 float 加在一起

c++ - 静态控件滚动条不工作 Win32

qt - 如何将 QLineEdit 默认文本设置为一个空格?

c++ - windows 8 IShellIconOverlayIdentifier 外壳扩展无法正常工作

python - 在不同线程中运行进度条 - Pyside

c++ - QThread在c++中的基本使用