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

一、说明
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 2021-03-04 09:31  一杯清酒邀明月  阅读(726)  评论(0编辑  收藏  举报