目录
简述
继承QThread,重写run()
继承QObject,通过moveToThread()移动到新线程
并发模块:QtConCurrent::run()
Qt提供了三种操作线程的方法:
注意:MyThread只有run函数是在新线程里的,其他所有函数都在创建MyThread的那个线程里。
MyThread类
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include
#include
class MyThread : public QThread
{
public:
explicit MyThread(){}
private:
void run() override //线程执行函数
{
qDebug()<<"new thread: "<< QThread::currentThreadId();
}
};
#endif // MYTHREAD_H
使用:
//定义线程
MyThread* thread;
//开始线程
thread = new MyThread;
thread->start();//使用该函数的时候会自动调用run函数
qDebug()<<"main thread: "<< QThread::currentThreadId();
//结束线程
thread->exit();
thread->deleteLater();
MyObject类
//线程处理对象
#ifndef MYOBJECT_H
#define MYOBJECT_H
#include
#include
#include
class MyObject : public QObject
{
Q_OBJECT
public:
explicit MyObject(QObject *parent = 0): QObject(parent){}
~MyObject(){}
private slots:
void Start()//线程处理函数
{
qDebug()<<"obj thread: "<
使用:
//定义变量
MyObject* obj;
QThread* thread;
//开始线程
obj = new MyObject;//线程执行对象
thread = new QThread;
obj->moveToThread(thread);//将对象移动到新建立的线程
connect(thread, &QThread::started, obj, &MyObject::Start);//绑定线程的开始信号,线程开始后就会执行obj的Start槽函数
thread->start();
qDebug()<<"main thread: "<exit();
thread->deleteLater();//删除对象
obj->deleteLater();
注意:使用QtConCurrent并发模块需要在文件中添加以下内容
pro文件:
QT += core concurrent
CONFIG += c++11
头文件:
#include
#include
使用Lambda表达式执行
//线程不做处理,直接返回5
void Widget::on_startBtn_clicked()
{
QFuture future = QtConcurrent::run([&]()
{
return 5; //线程执行代码区域
});
future.waitForFinished();//阻塞等待
qDebug()<<"result: "<< future.result();
}
线程执行类成员函数(不带参数)
//线程不做处理,直接返回5
int Widget::function()//线程执行函数
{
return 5;
}
void Widget::on_startBtn_clicked()
{
QFuture future = QtConcurrent::run(this, &Widget::function);
future.waitForFinished();
qDebug()<<"result: "<< future.result();
}
线程执行类成员函数(带参数)
//线程执行加法操作
int Widget::function(int a, int b)//线程执行函数
{
return a + b;
}
void Widget::on_startBtn_clicked()
{
QFuture future = QtConcurrent::run(this, &Widget::function, 3, 5);
future.waitForFinished();
qDebug()<<"result: "<< future.result();
}