QtC++报错QThread: Destroyed while thread is still running
时间: 2024-03-10 10:40:21 浏览: 25
这个错误通常是由于在QThread对象被销毁之前,线程仍在运行。这可能是因为您没有正确地停止线程或等待线程完成。您可以尝试在QThread对象销毁之前调用wait()函数来等待线程完成。如果您的线程是无限循环的,请确保在循环中使用QThread::isInterruptionRequested()来检查线程是否应该停止,并在需要时调用QThread::quit()和QThread::wait()来停止线程。
以下是一个示例代码,演示如何正确停止线程并避免此错误:
```cpp
// MyThread.h
#include <QThread>
class MyThread : public QThread
{
public:
void stop();
protected:
void run();
private:
volatile bool m_stopped;
};
// MyThread.cpp
#include "MyThread.h"
void MyThread::stop()
{
m_stopped = true;
}
void MyThread::run()
{
m_stopped = false;
while (!m_stopped)
{
// do some work
msleep(100);
}
}
// 在主线程中使用线程
MyThread* thread = new MyThread();
thread->start();
// ...
thread->stop();
thread->wait();
delete thread;
```