qt中線程的使用方法
阿新 • • 發佈:2017-11-28
widget public while sta back art 靜態變量 函數 file
QT中使用線程可以提高工作效率。
要使用線程要經過一下四個步驟:
(1)先創建一個c++ class文件,記得繼承Thread,創建步驟如下:
a、第一步
b、第二步
(2)自定義一個run函數,以後啟動線程的時候,程序就會跳轉到run函數中
void run();
(3)初始化線程
HDThread mythread = new HDThread();
(4)啟動線程
mythread->start();
下面來看看線程使用的具體列子:
線程頭文件hdthread.h:
1 #ifndef HDTHREAD_H 2 #define HDTHREAD_H 3 #include <QThread> 4 #include <QLabel> 5 #include <QMutex> 6 7 class HDTHread : public QThread 8 { 9 public: 10 HDTHread(QMutex* mtex,QObject *parent = 0); 11 void run();//自定義的run函數 12 void setLabel(QLabel *lb); 13 private: 14 QLabel *label; 15 QMutex *mutex; //互斥鎖 16 }; 17 18 #endif // HDTHREAD_H
主函數的頭文件threadqt.h
1 #ifndef THREADQT_H 2 #define THREADQT_H 3 4 #include <QMainWindow> 5 #include <hdthread.h> 6 #include <writefile.h> 7 #include <QMutex> 8 #include <QSemaphore> 910 namespace Ui { 11 class ThreadQt; 12 } 13 14 class ThreadQt : public QMainWindow 15 { 16 Q_OBJECT 17 18 public: 19 explicit ThreadQt(QWidget *parent = 0); 20 ~ThreadQt(); 21 22 //定義靜態的信號類 23 static QSemaphore *sp_A; 24 static QSemaphore *sp_B; 25 private slots: 26 void on_pushButton_clicked(); 27 28 private: 29 Ui::ThreadQt *ui; 30 31 HDTHread *thread; //hdtread類,裏面繼承了線程 32 WriteFile *writethread; 33 QMutex mutex;//定義互斥鎖類 34 35 }; 36 37 #endif // THREADQT_H
源文件hdthread.cpp:
#include "hdthread.h" #include <QDebug> #include <threadqt.h> HDTHread::HDTHread(QMutex *mtex, QObject *parent):QThread(parent)//構造函數,用來初始化 { this->mutex = mtex; } void HDTHread::setLabel(QLabel *lb) { this->label = lb; } void HDTHread::run() //啟動線程時執行的函數 { while(true) { qint64 data = qrand()%1000; //取隨機數 //this->mutex->lock();//上鎖 ThreadQt::sp_A->acquire();//請求信號 this->label->setText(QString::number(data)); sleep(1); ThreadQt::sp_B->release();//釋放信號 //this->mutex->unlock();//解鎖 qDebug()<<"hello Qt"<<data; } }
源文件threadqt.cpp
#include "threadqt.h" #include "ui_threadqt.h" //初始化靜態變量 QSemaphore *ThreadQt::sp_A = NULL; QSemaphore *ThreadQt::sp_B = NULL; ThreadQt::ThreadQt(QWidget *parent) : QMainWindow(parent), ui(new Ui::ThreadQt) { ui->setupUi(this); //創建信號對象 sp_A = new QSemaphore(1); sp_B = new QSemaphore(0); } ThreadQt::~ThreadQt() { delete ui; } void ThreadQt::on_pushButton_clicked() { thread = new HDTHread(&mutex); //初始化線程 thread->setLabel(ui->label); thread->start();//開啟線程 writethread = new WriteFile(&mutex); writethread->setLabel(ui->label); writethread->start(); }
大家也看到了,此處的線程也用到了互斥鎖(信號量)保證線程讀寫數據時不出現錯誤,這裏大家可以看一下具體實現的代碼
this->mutex->lock();//上鎖
ThreadQt::sp_A->acquire();//請求信號
this->label->setText(QString::number(data));
sleep(1);
ThreadQt::sp_B->release();//釋放信號
this->mutex->unlock();//解鎖
qt中線程的使用方法