本示例采用继承QThread的方式创建线程,在创建的子线程中计数,并将计数的数值通过信号与槽的方式发送至主线程,在主线程的UI界面上显示出来。
工程包含thread.h、thread.cpp 、widget.h、widget.cpp、main.cpp五个文件。其中thread.h 和 thread.cpp中为自己创建的线程类my_thread,继承自QThread。
基本用法如下:
假如自己创建的线程名为my_thread,创建线程对象指针。
my_thread = *test_thread;
test_thread = new my_thread(); //创建对象,与创建QT其他对象不同的是对象类型的括号中不可加this。
线程开始:
test_thread->start(); //启动线程
线程结束:
test_thread->stop(); //停止线程
test_thread->wait(); //等待线程退出
注意:
只有在run函数中运行的代码段才属于创建的新线程,其他都属于主线程。
参考代码示例如下:
thread.h文件
#ifndef THREAD_H
#define THREAD_H
#include <QString>
#include <QThread> //线程相关头文件
#include <QMutex> //互斥锁相关头文件
class my_thread :public QThread
{
Q_OBJECT
public:
my_thread();
virtual void run(); //线程函数,新创建的线程运行该函数内容。
void stop(); //停止线程
signals:
void send(QString msg); //发送信号
private:
bool flagRunning; //运行标志
QMutex mutex; //互斥锁
int count; //计数值
};
#endif // THREAD_H
thread.cpp文件
#include "thread.h"
#include <QDebug>
my_thread::my_thread()
{
flagRunning = true;
count = 0; //计数值初始化
}
void my_thread::run()
{
qDebug()<<"Creat pthread !!";
flagRunning = true;
mutex.lock(); //互斥锁加锁,在多线程中经常使用,这样可以解决资源竞争的问题(即不同线程同时访问同一资源的问题)。
while(flagRunning)
{
mutex.unlock();
emit send(QString::number(count)); //发送计数值
msleep(500);
mutex.lock();
count++; //计数
}
mutex.unlock(); //互斥锁解锁
qDebug()<<"Pthread exit!!";
}
void my_thread::stop()
{
mutex.lock();
flagRunning = false; //线程退出标志
mutex.unlock();
}
wiget.h文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QString>
#include "thread.h"
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
void text();
public slots:
void accept(QString msg); //接收子线程发送的信号的槽函数
private slots:
void on_pushButton_clicked(); //线程开始按钮
void on_pushButton_2_clicked(); //点击线程结束按钮
private:
Ui::Widget *ui;
my_thread *test_thread; //定义线程类型指针
};
#endif // WIDGET_H
widget.cpp文件
#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
test_thread = new my_thread(); //创建线程对象
QObject::connect(test_thread, SIGNAL(send(QString)), this, SLOT(accept(QString)));//连接信号与槽
}
Widget::~Widget()
{
delete ui;
}
void Widget::accept(QString msg)
{
ui->label->setText(msg); //将计数值显示出来
qDebug()<<msg;
}
void Widget::on_pushButton_clicked()
{
test_thread->start(); //启动线程
}
void Widget::on_pushButton_2_clicked()
{
test_thread->stop(); //停止线程
test_thread->wait(); //等待线程退出
}
main.cpp文件
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
程序运行效果:
示例代码链接:https://download.csdn.net/download/fangye945a/10841468