• Qt QtConcurrent::Run 阻塞方式调用


    一、说明
    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 }

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

  • 相关阅读:
    RestTemplate方法总结
    服务器上获取不到header中设置的自定义的属性值
    记录一次 事务问题 的处理
    java 集合按照 数值排序,如果数值一致 按照名字首字母排序
    mysql中按照中文首字母A-Z排序
    java 关于小数 换算整数 的一点想法
    mysql 根据身份证查询 年龄 性别
    MySQL普通索引(BTREE索引)以及最左前缀匹配
    net.sf.json的常用api
    Object划分
  • 原文地址:https://www.cnblogs.com/ybqjymy/p/14478372.html
Copyright © 2020-2023  润新知