void test()
{
MyThread t;
t.start();
}
void TestThread::run()
{
qDebug() << "void TestThread::run() -- begin tid = " << currentThreadId();
for(int i=0; i<3; i++)
{
qDebug() << "void TestThread::run() i = " << i;
sleep(1);
}
emit testSignal();
exec();
qDebug() << "void TestThread::run() -- end";
}
//会出现操作已经销毁的变量
解决方案1:
SyncThread::~SyncThread()
{
wait();
qDebug() << "SyncThread::~SyncThread() destroy thread object";
}
// 函数要等到对应的线程结束返回才往下走。
解决方案2:
线程对象不能被外界主动销毁(所以要把构造函数,析构函数保护起来)是指使用Delete 这样的关键字去销毁对象。
需要使用二阶构造模式
//AsyncThread.h
class AsyncThread : public QThread
{
Q_OBJECT
protected:
void run();
explicit AsyncThread(QObject *parent = 0);
~AsyncThread();
public:
static AsyncThread* NewInstance(QObject *parent = 0);
};
//AsyncThread .c
AsyncThread* AsyncThread::NewInstance(QObject *parent)
{
return new AsyncThread(parent);
}
AsyncThread::AsyncThread(QObject *parent) :
QThread(parent)
{
}
void AsyncThread::run()
{
qDebug() << "void AsyncThread::run() tid = " << currentThreadId();
for(int i=0; i<3; i++)
{
qDebug() << "void AsyncThread::run() i = " << i;
sleep(1);
}
qDebug() << "void AsyncThread::run() end";
deleteLater();
}
AsyncThread::~AsyncThread()
{
qDebug() << "AsyncThread::~AsyncThread() destroy thread object";
}
// main.c
void async_thread()
{
AsyncThread* at = AsyncThread::NewInstance();
at->start();
}