今天给大家介绍三种QT里面使用多线程的方法
1、继承QThread并且重写run方法来实现多线程
1 #ifndef MYQTHREAD_H 2 #define MYQTHREAD_H 3 #include <QMutex> 4 #include <QThread> 5 class myQThread : public QThread 6 { 7 public: 8 myQThread() 9 { 10 _isRunning = false; 11 } 12 void run() 13 { 14 while(true) 15 { 16 _mutex.lock(); 17 if(!_isRunning) 18 { 19 qDebug() << "myqthread" << QThread::currentThreadId(); 20 }else 21 { 22 _mutex.unlock(); 23 break; 24 } 25 _mutex.unlock(); 26 QThread::msleep(2000); 27 } 28 _isRunning = false; 29 } 30 void stop() 31 { 32 _mutex.lock(); 33 _isRunning = true; 34 _mutex.unlock(); 35 this->quit(); 36 this->wait(); 37 } 38 39 volatile bool _isRunning; 40 QMutex _mutex; 41 }; 42 43 #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里面三种多线程介绍到这里