#include "OneThread.h" #include OneThread::OneThread(QThread* thread, QObject* parent) : QObject(parent), m_thread(thread) { m_timerStartThread.setTimerType(Qt::PreciseTimer); m_timerStartThread.setSingleShot(true); /* 将自身移动到子线程中去 */ this->moveToThread(m_thread); /* 连接信号和槽 */ connect(&m_timerStartThread, &QTimer::timeout, this, &OneThread::do_timeoutWork); connect(this, &OneThread::signal_startThread, this, &OneThread::do_timeoutWork); /* 指定为队列连接 */ connect(this, &OneThread::signal_runTask, this, &OneThread::do_runTask,Qt::QueuedConnection); /* 注册数据类型 */ qRegisterMetaType>("std::function"); qRegisterMetaType >("std::function"); } OneThread::~OneThread() { if(m_thread != nullptr) { m_thread->quit(); m_thread->wait(); // delete m_thread; m_thread = nullptr; } } /* 开启线程 */ void OneThread::startThread() { m_timerStartThread.start(0); } /* 线程函数 */ void OneThread::do_timeoutWork() { qDebug() << "----- do_timeoutWork , Thread ID: " << QThread::currentThreadId(); // emit signal_runTask(m_func); qDebug() << "----- do_timeoutWork end -----"; } /* 传入函数,运行函数 */ void OneThread::do_runTask(std::function func) { qDebug() << "----- do_runTask , Thread ID: " << QThread::currentThreadId(); func(); qDebug() << "----- do_runTask end -----"; }