一杯清酒邀明月
天下本无事,庸人扰之而烦耳。

一、说明
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 }
复制代码

三、结果
在这里插入图片描述

posted on   一杯清酒邀明月  阅读(788)  评论(0编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示