QMutex 및 QWaitCondition을 사용하여 구현 된 일시 중지/다시 시작 메커니즘과 함께 QThread를 사용하는 C++ Qt 프로그램이 있습니다. 즉, 보이는 방법은 다음과 같습니다QMutex with QThread - 분할 오류
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 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()
전화 :
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 클래스의 벡터를 사용 메서드가 MyClass
인 경우 세그먼트 오류 신호가 MyT의 3 행으로 (디버그 모드에서) 지정됩니다. hread.cpp - syncMutex.lock();
. MyThread
인스턴스의 양에 의존하지 않습니다. std :: vector에서 1 스레드로도 중단됩니다.
나는 중요한 무엇인가 놓친다 고 확신하지만, 나는 무엇을 모른다. 내가 도대체 뭘 잘못하고있는 겁니까?
는 벡터에 포함 된 항목 수를 알아 루프의 대신 sizeof(this->threadsVector)
의 this->threadsVector.size()
을 사용
대기 조건에 사용하는 뮤텍스와 동일한 부울을 지키지 않고 QAtomicBool을 사용하는 것이 좋습니다. – milianw