QT多线程的使用

今天给大家介绍三种QT里面使用多线程的方法

1、继承QThread并且重写run方法来实现多线程

 #ifndef MYQTHREAD_H
#define MYQTHREAD_H
#include <QMutex>
#include <QThread>
class myQThread : public QThread
{
public:
myQThread()
{
_isRunning = false;
}
void run()
{
while(true)
{
_mutex.lock();
if(!_isRunning)
{
qDebug() << "myqthread" << QThread::currentThreadId();
}else
{
_mutex.unlock();
break;
}
_mutex.unlock();
QThread::msleep();
}
_isRunning = false;
}
void stop()
{
_mutex.lock();
_isRunning = true;
_mutex.unlock();
this->quit();
this->wait();
} volatile bool _isRunning;
QMutex _mutex;
}; #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里面三种多线程介绍到这里

上一篇:ZAB协议(转)


下一篇:git版本号管理工具的上手