1

QMutex と QWaitCondition を使用して実装された一時停止/再開メカニズムを備えた QThread を使用する C++ Qt プログラムがあります。それがどのように見えるかです:

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

pause()のメソッドを呼び出すとMyClass、(デバッグ モードで) MyThread.cpp の 3 行目を指しているセグメンテーション エラー シグナルが表示されますsyncMutex.lock();。インスタンスの量には依存しませんMyThread- std::vector に 1 つのスレッドがあっても壊れます。

何か重要なものを見逃したと確信していますが、何がわかりません。私は何を間違っていますか?

(問題がある場合は、Qt 5 で MinGW 4.7 コンパイラを使用します)

4

1 に答える 1

5

for ループでは、this->threadsVector.size()代わりにを使用sizeof(this->threadsVector)して、ベクターに含まれるアイテムの数を調べます。

于 2013-05-17T15:35:08.670 に答える