首页 > 其他分享 >QtConcurrent::run()多线程的同步、异步

QtConcurrent::run()多线程的同步、异步

时间:2023-12-09 19:22:06浏览次数:33  
标签:多线程 run QFuture QFutureWatcher QtConcurrent include

Qt 提供了 QtConcurrent 模块,处理一些常见的并行计算,最大的特点就是无需再使用互斥锁这种很低级的操作,全都封装好了。除此以外,QFuture、QFutureWatcher、QFutureSynchronizer 类提供了一些辅助性的操作。参考:Qt 中的多线程技术 - 知乎 (zhihu.com)

【QtConcurrent::run() 需注意】

  • 默认扔进了全局线程池,即 QThreadPool::globalInstance()
  • 传参数的时候,都会复制一份副本。即使参数是引用,在函数中修改数据也不会对源对象产生任何影响。
  • QFuture::result() 与 QFuture::waitForFinished()函数都会阻塞,直到结果可用才继续之后的代码。
  • QtConcurrent::run()返回的QFuture不支持取消、暂停和进度报告。返回的QFuture只能用于查询运行/完成状态和函数的返回值。

可以执行无参、含参、有返回值函数,以及lambda表达式。参考Qt多线程编程之高级函数 - 知乎 (zhihu.com) 和 Qt 多线程的几种实现方式 - 知乎 (zhihu.com)

【QFutureWAtcher】

QFuture::result() 会阻塞,若不想一直等待结果,可以使用QFutureWAtcher获取通知。

参考 QT高级线程API总结(一)QtConcrrent::run_qtconcurrent::run(qthreadpool::globalinstance(), [-CSDN博客

QByteArray bytearray = "hello ,world";
QFuture<QString > future = QtConcurrent::run(this, &MainWindow::threadFunc, bytearray);
//QFutureWatcher<QString> *m_watcher = new QFutureWatcher<QString>(this);
m_watcher = new QFutureWatcher<QString>(this);
m_watcher->setFuture(future);
connect(m_watcher, &QFutureWatcher<QString>::finished, [=](){
    qDebug() << "finished";
});
 
QString MainWindow::threadFunc(QByteArray &arg){
    qDebug() << "threadFunc:" << arg;
 
    //do process...
    return QString("");
};

【QFutureSynchronizer】

为了简化多个QFuture的同步等待操作,特地为我们提供了一个模板类QFutureSynchronizer。

参考 使用QFuture类监控异步计算的结果 - findumars - 博客园 (cnblogs.com)

#include <QCoreApplication>
#include <QFuture>
#include <QFutureSynchronizer>
#include <QtConcurrent>
#include <QDebug>

//计算第lindex 个 斐波那契数值
qulonglong Fibonacci(int index)
{
qulonglong f1 = 1, f2 = 1, cur = 0;
for(int i = 3; i <= index; i++)
{
cur = f1 + f2;
f1 = f2;
f2 = cur;
}
return cur;
}

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

QFutureSynchronizer<qulonglong> synchronizer;
synchronizer.addFuture(QtConcurrent::run(Fibonacci, 50));
synchronizer.addFuture(QtConcurrent::run(Fibonacci, 100));
synchronizer.waitForFinished();
qDebug() << "第50个斐波那契数: " << synchronizer.futures()[0].result();
qDebug() << "第100个斐波那契数: " << synchronizer.futures()[1].result();

return a.exec();
}

 

标签:多线程,run,QFuture,QFutureWatcher,QtConcurrent,include
From: https://www.cnblogs.com/xixixing/p/17891352.html

相关文章

  • pytest + yaml 框架 -59.用例失败重跑机制pytest-rerunfailures
    前言有些接口可能不太稳定,第一次跑的时候由于网络原因或者其它原因失败,但是重新跑2次又成功了。对于这种需要重新跑几次的场景,可以使用用例失败重跑机制,需安装pytest-rerunfailures插件。场景示例失败重跑需要依赖pytest-rerunfailures插件,使用pip安装就行pipinstallp......
  • nerdctl run -d 报"failed to call cni.Setup: plugin type=\"bridge\" failed (ad
    背景:执行 nerdctl run-d --namenginx-p8080:80nginx时,报如下错误FATA[0000]failedtocreateshimtask:OCIruntimecreatefailed:runccreatefailed:unabletostartcontainerprocess:errorduringcontainerinit:errorrunninghook#0:errorrunningh......
  • Redis报错:(error) DENIED Redis is running in protected mode because protected mod
    一、报错内容  (error)DENIEDRedisisrunninginprotectedmodebecauseprotectedmodeisenabledandnopasswordissetforthedefaultuser.Inthismodeconnectionsareonlyacceptedfromtheloopbackinterface.Ifyouwanttoconnectfromexternal......
  • SpringBoot+线程池实现高频调用http接口并多线程解析json数据
    场景Springboot+FastJson实现解析第三方http接口json数据为实体类(时间格式化转换、字段包含中文):https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/134872936Java中ExecutorService线程池的使用(Runnable和Callable多线程实现):https://blog.csdn.net/BADAO_LIUMAN......
  • 容器启动流程(containerd 和 runc)
    启动流程containerd作为一个api服务,提供了一系列的接口供外部调用,比如创建容器、删除容器、创建镜像、删除镜像等等。使用docker和ctr等工具,都是通过调用containerd的api来实现的。kubelet通过cri调用containerd和这些不一样,后续我会介绍到。containerd创建容......
  • @SpringBootTest与@RunWith注解的区别
    @SpringBootTest与@RunWith注解的区别@SpringBootTest与@RunWith注解的区别在于:@SpringBootTest是spring的注解,用于加载ApplicationContext,启动spring容器;而@RunWith是junit的注解,它指定了junit测试的时候使用的Runner(运行器)类。通常@SpringBootTest与@RunWith这两个是配合使......
  • @RunWith(SpringRunner.class)注解的作用
    @RunWith(SpringRunner.class)注解的作用通俗点:@RunWith(SpringRunner.class)的作用表明Test测试类要使用注入的类,比如@Autowired注入的类,有了@RunWith(SpringRunner.class)这些类才能实例化到spring容器中,自动注入才能生效官方点:@RunWith注解是JUnit测试框架中的一种注解,......
  • onnxruntime GPU 推理错误
    错误[E:onnxruntime:Default,provider_bridge_ort.cc:1480TryGetProviderInfo_CUDA]/onnxruntime_src/onnxruntime/core/session/provider_bridge_ort.cc:1193onnxruntime::Provider&onnxruntime::ProviderLibrary::Get()[ONNXRuntimeError]:1:FAIL:Failedto......
  • Golang标准库:runtime/debug 包代码示例
    runtime/debug包提供了与运行时调试和诊断相关的功能。以下是一个示例代码,展示了如何使用runtime/debug包的一些功能:packagemainimport( "fmt" "runtime/debug")funcmain(){ //获取当前goroutine的栈跟踪信息 stackTrace:=debug.Stack() //打印栈跟踪信息......
  • Golang runtime包代码示例
    在Go中,runtime包提供了与运行时系统(runtimesystem)交互的功能。这个包包含了一些底层的运行时操作,例如内存管理、协程管理、垃圾回收等。以下是一个简单的示例代码,展示了runtime包的一些常见用法:packagemainimport( "fmt" "runtime")funcmain(){ //获取Go程序......