#include "OneThread.h" #include #include OneThread::OneThread(QThread* thread, QObject* parent) : QObject(parent), m_thread(thread) { /* 将自身移动到子线程中去 */ this->moveToThread(m_thread); /* 指定为队列连接 */ connect(this, &OneThread::signal_runTask, this, &OneThread::do_runTask,Qt::QueuedConnection); /* 注册数据类型 */ qRegisterMetaType>("std::function"); qRegisterMetaType >("std::function"); /* 连接信号和槽 */ connect(this, &OneThread::signal_runTask, this, &OneThread::do_runTask); connect(this, &OneThread::signal_runTaskRunOne, this, &OneThread::do_runTaskRunOne); } OneThread::OneThread(QObject* parent) : QObject(parent) { m_thread = new QThread(); /* 将自身移动到子线程中去 */ this->moveToThread(m_thread); /* 指定为队列连接 */ connect(this, &OneThread::signal_runTask, this, &OneThread::do_runTask,Qt::QueuedConnection); /* 注册数据类型 */ qRegisterMetaType>("std::function"); qRegisterMetaType >("std::function"); /* 连接信号和槽 */ connect(this, &OneThread::signal_runTask, this, &OneThread::do_runTask); connect(this, &OneThread::signal_runTaskRunOne, this, &OneThread::do_runTaskRunOne); } OneThread::~OneThread() { if(m_thread != nullptr) { m_thread->quit(); m_thread->wait(); // delete m_thread; m_thread = nullptr; } } /* 传入函数,运行函数 */ void OneThread::do_runTask(std::function func) { qDebug() << "----- do_runTask , Thread ID: " << QThread::currentThreadId(); m_threadRunning = true; while(m_threadRunning) { func(); /* 进入事件循环 */ QCoreApplication::processEvents(); /* 延时1ms */ QThread::usleep(100); } qDebug() << "----- do_runTask end -----"; } void OneThread::do_runTaskRunOne(std::function func) { func(); }