Qt 多线程QThreadPool

网友投稿 533 2022-05-30

开发环境 Qt5.5.1、Qt Creator 3.5.1

#include

#include

#include

#include

#include

#include

class MyRunnable;

//事件类

class MyEvent: public QEvent {

public:

MyRunnable *m_runnable;

QString m_message;

MyEvent(MyRunnable *r, QString message): QEvent(eventType()), m_runnable(r), m_message(message) { }

static QEvent::Type eventType(){

if(s_eventType == QEvent::None) {

//注册一个自定义类型1000-65535

s_eventType = (QEvent::Type)registerEventType();

//qDebug()<<"registerEventType "<<(int)s_eventType;

}

return s_eventType;

}

private:

static QEvent::Type s_eventType;

};

QEvent::Type MyEvent::s_eventType = QEvent::None;

//线程的耗时操作

class MyRunnable :public QRunnable{

public:

MyRunnable(QObject* observer): m_observer(observer){

}

//Override

void run();

private:

//QPointer是为QObject对象提供保护指针的模板类

//一个保护指针 QPointer,行为类似正常的C++指针,只不过其在引用对象删除之后会自动设置为0. T必须是QObject的子类

//保护指针在你要保存别人创建的QObject对象,且有可能其已经被删除而你仍然持有其引用的时候非常有用。

//Qt也提供QSharedPointer,一个基于引用计数的共享指针对象实现,其能使用单个指针用于维护一个引用集合

//就是说,如果指代的对象被删除,则后面对该对象的所有操作不会执行,因此也不会抛异常

QPointer m_observer;

};

//Override

void MyRunnable::run() {

QString message;

message.append(QString::number((int)QThread::currentThreadId())+" start\r\n");

message.append(QThread::currentThread()->objectName()+"\r\n");

QThread::sleep(1);

message.append(QString::number((int)QThread::currentThreadId())+" end\r\n");

QCoreApplication::postEvent(m_observer, new MyEvent(this, message));

}

//主程序中的消息处理程序

class MyProcesser: public QObject {

public:

MyProcesser() {

}

//Override

bool event(QEvent *);

void process();

void abort();

Qt 多线程(QThreadPool)

private:

QList m_runnableList;

};

bool MyProcesser::event(QEvent *e) {

if(e->type() == MyEvent::eventType()) {

qDebug()<<"processer get event, type is "<<(int)e->type();

qDebug()<<((MyEvent*)e)->m_message;

m_runnableList.removeOne(((MyEvent*)e)->m_runnable);

}

}

void MyProcesser::process() {

MyRunnable* runnable = new MyRunnable(this);

m_runnableList.append(runnable);

//是否线程池替你删除

//If auto-deletion is enabled, QThreadPool will automatically delete this runnable after calling run();

//otherwise, ownership remains with the application programmer.

runnable->setAutoDelete(false);

QThreadPool::globalInstance()->start(runnable);

}

void MyProcesser::abort() {

int size = m_runnableList.size();

MyRunnable* r;

for(int i=0;i

r = m_runnableList.at(i);

m_runnableList.removeAt(i);

}

}

int main(int argc, char *argv[])

{

QCoreApplication a(argc, argv);

qDebug()<<"main thread "<

qDebug()<<"main thread "<objectName();

MyProcesser processer;

processer.process();

processer.process();

return a.exec();

}

Qt 任务调度 多线程

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Go语言为并发而生
下一篇:【愚公系列】2022年02月 微信小程序-app.json配置属性之Worker
相关文章