Question

I have a C++ Qt program that uses QThread with pause/resume mechanism implemented using QMutex and QWaitCondition. That's how it looks:

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
    }
}

I use a vector of MyThread classes:

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();
    }
}

When I call pause() method of MyClass, I get Segmentation fault signal pointing (in Debug mode) to line 3 in MyThread.cpp - syncMutex.lock();. It does not depend on the amount of MyThread instances - it breaks even with 1 thread in the std::vector.

I'm pretty sure I missed something important, but I don't know what. What am I doing wrong?

(If it does matter, I use MinGW 4.7 compiler with Qt 5)

Was it helpful?

Solution

In the for loops use this->threadsVector.size() instead of sizeof(this->threadsVector) to find out how many items the vector contains.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top