一、说明
Concurrent是并发的意思,QtConcurrent是一个命名空间,提供了一些高级的 API,使得在编写多线程的时候,无需使用低级线程原语,如读写锁,等待条件或信号。使用QtConcurrent编写的程序会根据可用的处理器内核数自动调整使用的线程数。
二、代码
1 #ifndef WIDGET_H
2 #define WIDGET_H
3
4 #include <QWidget>
5
6 QT_BEGIN_NAMESPACE
7 namespace Ui { class Widget; }
8 QT_END_NAMESPACE
9
10 class item
11 {
12 public:
13 item();
14 ~item();
15 static void hello(const QString &str);
16 };
17
18 class Widget : public QWidget
19 {
20 Q_OBJECT
21
22 public:
23 Widget(QWidget *parent = nullptr);
24 ~Widget();
25 static void hello(const QString &str);
26
27 private:
28 Ui::Widget *ui;
29 private:
30 void sig();
31
32 };
33 #endif // WIDGET_H
1 #include "widget.h"
2 #include "ui_widget.h"
3 #include <QDebug>
4 #include <QThread>
5 #include <QtConcurrent>
6 #include <QtConcurrentRun>
7 #include <QFuture>
8
9 Widget::Widget(QWidget *parent)
10 : QWidget(parent)
11 , ui(new Ui::Widget)
12 {
13 ui->setupUi(this);
14 qDebug()<<"main thread:"<<QThread::currentThread();
15
16 QFuture<void> f1 = QtConcurrent::run(hello,QString("demo1"));
17 QFuture<void> f2 = QtConcurrent::run([=]{
18 item::hello("demo2");
19 });
20 f1.waitForFinished();
21 f2.waitForFinished();
22 }
23
24 Widget::~Widget()
25 {
26 delete ui;
27 }
28
29 void Widget::hello(const QString &str)
30 {
31 qDebug()<<"Widget hello"<<str<<"from"<<QThread::currentThread();
32 }
33
34 void item::hello(const QString &str)
35 {
36 qDebug()<<"item hello"<<str<<"from"<<QThread::currentThread();
37 }
三、结果
分类:
Qt
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)