栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Qt入门系列开发教程【Core篇】多线程QThread、QRunnable、QtConcurrent

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Qt入门系列开发教程【Core篇】多线程QThread、QRunnable、QtConcurrent

「作者主页 」:鱼酱2333
「 B站首页 」:鱼酱2333
「本文录入专栏」:Qt入门系列开发教程
「本文内容」:Qt中的多线程

文章目录

1.线程2.Qt创建线程的方法3.使用场景4.线程使用实例

1.线程

线程(英语:thread)是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。

大白话版:线程就是一个程序里面包含多个人,每个人干自己的事

2.Qt创建线程的方法

Qt中创建多线程有三种方式

继承QThread类继承QRunnable,使用QThreadPool启动QRunnable对象QtConcurrent使用多核开启

QThread:想要使用信号,最简单起线程方式

QRunnable:全局线程池,不用信号。频繁创建于销毁。

QtConcurrent:多核心开启,无法使用信号与槽,利用计算机多核的场景。

3.使用场景

特性

特性QThreadQRunableQtConcurrent
高级API××
面向任务×
内建对暂停/回复/取消的支持××
具有优先级××
可运行消息循环××

使用场景

需要线程的生命周期开发场景解决方案
单次调用在其他的线程中运行一个方法,当方法运行结束后退出线程。1.编写一个函数,然后利用 QtConcurrent::run()运行它
2.从QRunnable 派生一个类,并利用全局线程池QThreadPool::globalInstance()->start()来运行它
3.从QThread派生一个类, 重载QThread::run() 方法并使用QThread::start()来运行它。
单次调用一个耗时的操作必须放到另一个线程中运行。在这期间,状态信息必须发送到GUI线程中。使用 QThread,重载run方法并根据情况发送信号。使用queued信号/槽连接来连接信号与GUI线程的槽。
常驻有一对象位于另一个线程中,将让其根据不同的请求执行不同的操作。这意味与工作者线程之间的通信是必须的。从QObject 派生一个类并实现必要的槽和信号,将对象移到一个具有事件循环的线程中,并通过queued信号/槽连接与对象进行通信。

4.线程使用实例

QThread

#include "mainwindow.h"

#include 
#include 

class DemoThread:public QThread
{
    virtual void run()override{
        //开启消息循环,之后的业务都用定时器开发即可
        //exec();
        while(true)
        {
            qDebug()< 

QRunnable

 class HelloWorldTask : public QRunnable
 {
     void run() override
     {
         qDebug() << "Hello world from thread" << QThread::currentThread();
     }
 };

 HelloWorldTask *hello = new HelloWorldTask();
 // QThreadPool takes ownership and deletes 'hello' automatically
 QThreadPool::globalInstance()->start(hello);

QtConcurrent

QT += concurrent

//第一种
QtConcurrent::run([this]()
{
	//todo
}
//第二种
#include 
#include 
#include 
 
void hello(const QString &name)
{
    qDebug() << "Hello" << name << "from" << QThread::currentThread();
}
 
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
 
    qDebug() << "Main Thread" << QThread::currentThread();
 
    // 在一个单独的线程中调用 hello()
    QFuture f1 = QtConcurrent::run(hello, QString("Qter"));
    QFuture f2 = QtConcurrent::run(hello, QString("Pythoner"));
 
    // 阻塞调用线程并等待计算完成,确保所有结果可用
    f1.waitForFinished();
    f2.waitForFinished();
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/705121.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号