月光下魔语,蒙阴天气预报,再世骄子
今天给大家介绍三种qt里面使用多线程的方法
1、继承qthread并且重写run方法来实现多线程
#ifndef myqthread_h
#define myqthread_h
#include <qthread>
class myqthread : public qthread
{
public:
myqthread();
void run();
};
#endif // myqthread_h
2、使用movetothread方法实现多线程,该类一定要继承qobject
#ifndef myobjectthread_h
#define myobjectthread_h
#include <qobject>
class myobjectthread : public qobject
{
q_object
public:
explicit myobjectthread(qobject *parent = nullptr);
signals:
public slots:
void showid();
};
#endif // myobjectthread_h
3、使用c++11的thread来实现多线程
#ifndef myc11thread_h
#define myc11thread_h
class myc11thread
{
public:
myc11thread();
void showc11id(int i);
};
#endif // myc11thread_h
4、来看一看这三种多线程如何使用
void showid(int i)
{
qdebug() << "全局函数的现成id" << qthread::currentthreadid() << "i:" << i;
}
mainwindow::mainwindow(qwidget *parent) :
qmainwindow(parent),
ui(new ui::mainwindow)
{
ui->setupui(this);
//qthread重写runfangfa
tmpmyqthread = new myqthread();
tmpmyqthread->start();
//用movetothread,但是这个类要继承object
qthread *th = new qthread;
tmpmyobject = new myobjectthread();
//把tmpmyobject这个类的对象放到线程中
tmpmyobject->movetothread(th);
//通过信号槽的方法,把槽函数运行在线程中
connect(th,signal(started()),tmpmyobject,slot(showid()));
th->start();
//c11原始的thread把全局函数初始化到线程
std::thread th1(showid,2);
th1.detach();
//c11原始thread把类的函数初始化到线程运行
tmpmyc11 = new myc11thread();
std::thread th2(&myc11thread::showc11id,tmpmyc11,2);
th2.detach();
qdebug() << "mainthread:" << qthread::currentthreadid();
}
qt里面三种多线程介绍到这里
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
如何在没有core文件的情况下用dmesg+addr2line定位段错误
用QT制作3D点云显示器——QtDataVisualization
网友评论