zoukankan      html  css  js  c++  java
  • 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 }

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

  • 相关阅读:
    SQL Server 2012提供的OFFSET/FETCH NEXT与Row_Number()对比测试
    sql 知识点
    javascript基础拾遗——词法作用域
    Linux 软件包管理
    涉略spring
    WebReBuild年会流水记
    javascript面向对象学习笔记(一)——继承
    算法学习——动态规划策略入门
    编程之美读书笔记——2.3寻找水王
    Linux 引导流程解析
  • 原文地址:https://www.cnblogs.com/ybqjymy/p/14478372.html
Copyright © 2011-2022 走看看