头文件:QWork.h
#pragma once
#include "qobject.h"
#include <QThread>
class QWork :
public QObject
{
Q_OBJECT
public:
QWork(int objID, QObject *parent = nullptr);
virtual ~QWork();
void ready();
signals:
void stopWork();
void next();
public slots :
void startWork();
private:
int m_objID{ 0 };
static QThread *sm_renderThread;
};
源文件:QWork.cpp
#include "QWork.h"
#include <iostream>
QWork::QWork(int objID, QObject *parent)
: m_objID(objID)
, QObject(parent)
{
}
QWork::~QWork()
{
emit stopWork();
}
void QWork::ready()
{
if (!QWork::sm_renderThread)
{
std::cout << "new QThread" << std::endl;
QWork::sm_renderThread = new QThread();
}
this->moveToThread(QWork::sm_renderThread);
connect(QWork::sm_renderThread, &QThread::started, this, &QWork::startWork, Qt::QueuedConnection);
connect(this, &QWork::stopWork, this, &QWork::deleteLater, Qt::QueuedConnection);
connect(this, &QWork::next, this, &QWork::startWork, Qt::QueuedConnection);
if (!QWork::sm_renderThread->isRunning())
{
QWork::sm_renderThread->start();
}
}
void QWork::startWork()
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::cout << "工作线程[" << std::this_thread::get_id() << "] 正在工作..." << std::endl;
std::cout << "我是Work: " << m_objID << std::endl;
emit next();
}
QThread * QWork::sm_renderThread = nullptr;
调用:main.cpp
#include <QtCore/QCoreApplication>
#include "QWork.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
for (unsigned int i = 0; i < 10; ++i)
{
QWork *work = new QWork(i);
work->ready();
}
return a.exec();
}