std::future ---C++17 多线程

std::future —C++17 多线程

std::future

C++标准程序库使用future来模拟这类一次性事件:若线程需等待某个特定的一次性事件发生,则会以恰当的方式取得一个future,它代表目标事件;接着,该线程就能一边执行其他任务(光顾机场茶座),一边在future上等待;同时,它以短暂的间隔反复查验目标事件是否已经发生(查看出发时刻表)。这个线程也可以转换运行模式,先不等目标事件发生,直接暂缓当前任务,而切换到别的任务,及至必要时,才回头等待future准备就绪。future可能与数据关联(如航班的登机口),也可能未关联。一旦目标事件发生,其future即进入就绪状态,无法重置。

总之,先保存一个事件(创建future对象),在未来获取事件的结果(get)

#pragma once
#include <future>
#include <iostream>
#include <format>
using namespace std;std::string get_answer_from_hard_question()
{std::this_thread::sleep_for(2s);cout << "id: " << std::this_thread::get_id << endl;return string("答案在这\n");
}
void do_something()
{std::this_thread::sleep_for(5s);cout << "id: " << std::this_thread::get_id << endl;cout << "结束任务\n";
}void start()
{std::future<std::string> the_ans = std::async(std::launch::async,get_answer_from_hard_question);do_something();std::cout << std::format("答案是:{}", the_ans.get());
}

创建future对象的方法

#include <string>
#include <future>
struct X
{void foo(int,std::string const&);std::string bar(std::string const&);
};
X x;    
auto f1=std::async(&X::foo,&x,42,"hello");---  ①调用p->foo(42,"hello"),其中p的值是&x,即x的地址
auto f2=std::async(&X::bar,x,"goodbye");---  ②调用tmpx.bar("goodbye"),其中tmpx是x的副本
struct Y                                
{double operator()(double);
}; 
Y y;
auto f3=std::async(Y(),3.141);---  ③调用tmpy(3.141)。其中,由Y()生成一个匿名变量,传递给std::async(),进而发生移动构造。在std::async()内部产生对象tmpy,在tmpy上执行Y::operator()(3.141) 
auto f4=std::async(std::ref(y),2.718);---  ④调用y(2.718)
X baz(X&);
std::async(baz,std::ref(x));---  ⑤调用baz(x)
class move_only
{
public:move_only();move_only(move_only&&)move_only(move_only const&) = delete;move_only& operator=(move_only&&);move_only& operator=(move_only const&) = delete;void operator()();
}; 
auto f5=std::async(move_only());---  ⑥调用tmp(),其中tmp等价于std::move (move_only()),它的产生过程与③相似

按默认情况下,std::async()的具体实现会自行决定——等待future时,是启动新线程,还是同步执行任务。大多数情况下,我们正希望如此。不过,我们还能够给std::async()补充一个参数,以指定采用哪种运行方式。参数的类型是std::launch,其值可以是std::launch::deferredstd::launch::async。前者指定在当前线程上延后调用任务函数,等到在future上调用了wait()get(),任务函数才会执行;后者指定必须另外开启专属的线程,在其上运行任务函数。该参数的值还可以是std::launch::deferred | std::launch:: async,表示由std::async()的实现自行选择运行方式。最后这项是参数的默认值。若延后调用任务函数,则任务函数有可能永远不会运行。举例如下。

auto f6=std::async(std::launch::async,Y(),1.2);---  ①运行新线程auto f7=std::async(std::launch::deferred,baz,std::ref(x));---  ②在wait()get()内部运行任务函数
auto f8=std::async(---  std::launch::deferred | std::launch::async,baz,std::ref(x));
auto f9=std::async(baz,std::ref(x));---  ③交由实现自行选择运行方式
f7.wait();---  ④前面②处的任务函数调用被延后,到这里才运行

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/407993.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

VNCserver在Fedora上配置过程

前言&#xff1a;一直想写一下vncserver在redhat下详细配置过程&#xff0c;以帮助一些向我有同样需求却有懒得去读man page的朋友&#xff0c;后来在www.fedoranews.org上发现已经有人写了一个教程&#xff0c;并且还不错。干脆翻译算了。大家可以直接去阅原文&#xff0c;我这…

学好英语的42个经典要诀(完整版)

第一要诀&#xff1a;收听英语气象报告 有些教学录音带为配合初学者的学习&#xff0c;故意放慢语速&#xff0c;这对英语听力的训练是不够的。如果听语速正常的英语&#xff0c;初学者又会感到力不从心。英语气象报告的速度虽快&#xff0c;但词汇简单固定&#xff0c;内容单纯…

std::packaged_task() ---C++17 并发编程

std::packaged_task() —C17 并发编程 std::packaged_task<>连结了future对象与函数&#xff08;或可调用对象&#xff09;。 std::packaged_task<>对象在执行任务时&#xff0c;会调用关联的函数&#xff08;或可调用对象&#xff09;&#xff0c;把返回值保存为…

js分页--存储数据并进行分页

//分页方法var page function(){this.v {o:null,//ul父级层home:null,previous:null,next:null,last:null, list:[],pageSize:10,pageIndex:0,pageCount:0,rowCount:0};this.init function(){var _this this;_this.v.o.find("li").each(function(i,o){_this.v.…

c/c++面试试题(一)

1.求下面函数的返回值&#xff08;微软&#xff09;int func(x) { int countx 0; while(x) { countx ; x x&(x-1); } return countx; } 假定x 9999。 答案&#xff1a;8思路&#xff1a;将x转化为2进制&#xff0c;看含有的1…

react(78)--vs打开setting.json

1.ctrl shift p 2.输入setting 3.找到这一项

stdspan ---C++20

std::span —C20 std::span的定义 template<class T,std::size_t Extent std::dynamic_extent > class span;std::span是指向一组连续的对象的对象, 是一个视图view, 不是一个拥有者owner 一组连续的对象可以是 C 数组, 带着大小的指针, std::array, 或者 std::strin…

2. Get the codes from GIT

Clone the code from git. Click the “GitEx Clone”. Paste the url into the “Repository to clone”. You can get the route from git repository from it: https://msstash.companydomainname.com/ .Find the project which you want to download and then click the “…

按钮控件数组

Public Class ButtonArray Inherits System.Collections.CollectionBase Private ReadOnly HostForm As System.Windows.Forms.Form 创建类的构造函数。 Visual Basic Public Sub New(ByVal host As System.Windows.Forms.Form) HostForm host Me.Add…

c/c++面试试题(二)

21. New delete 与malloc free 的联系与区别?答案&#xff1a;都是在堆(heap)上进行动态的内存操作。用malloc函数需要指定内存分配的字节数并且不能初始化对象&#xff0c;new 会自动调用对象的构造函数。delete 会调用对象的destructor&#xff0c;而free 不会调用对象的des…

The Ranges Library (2) --- C++20

The Ranges Library (2) — C20 比较std与std::ranges算法 比较一下std::sort和std::ranges::sort std::sort template< class RandomIt > constexpr void sort( RandomIt first, RandomIt last );template< class ExecutionPolicy, class RandomIt > void sor…

react(79)--ant design确认框

<Popconfirmplacement"rightBottom"title{text}onConfirm{confirm}okText"Yes"cancelText"No"><Button>RB</Button></Popconfirm>

程序中的得与失

俗话说&#xff0c;舍得&#xff0c;有舍便有得&#xff0c;程序或许和世间万物一个样&#xff0c;讲究阴阳平衡。或许您写程序过程中&#xff0c;得到一颗歪脖树&#xff0c;却放弃了一大片大森林&#xff0c;能正确的取舍矛盾体双方的关系&#xff0c;或许是您扎实功底的体现…

[转]新东方老师上课讲的笑话(太有才了)

[张洪伟] 起名字的问题&#xff1a;中西方都不愿意以鲜花、野草起名字&#xff0c;什么牡丹玫瑰&#xff0c;小红小翠了&#xff0c;一听就变味了&#xff1b;张建、李建&#xff0c;但不能叫范建&#xff08;贱&#xff09;了&#xff1b;北京以前有个建&#xff08;贱&#x…

c/c++面试试题(三)

慧通&#xff1a; 什么是预编译何时需要预编译&#xff1a;&#xff11;、总是使用不经常改动的大型代码体。 &#xff12;、程序由多个模块组成&#xff0c;所有模块都使用一组标准的包含文件和相同的编译选项。在这种情况下&#xff0c;可以将所有包含文件预编译为一个预编译…

mysql安装使用--2 用户管理

1 修改mysql.user表 添加用户 mysql> INSERT INTO mysql.user (Host,User,Password) VALUES (\%\,\system\, PASSWORD(\manager\)); mysql> FLUSH PRIVILEGES 2 create 和 grant命令省略 3 user表内容 MySQL用户名由两部分组成&#xff1a;(user, host)&#xff0c;二者…

constexpr if --- C++ 20

constexpr if — C 20 constexpr if 可以让我们实现条件编译 template <typename T> auto getResult(T t) {if constexpr (std::is_integral_v<T>)return *t;elsereturn t; }如果T是intergral类型,执行第一个分支,否则执行第二个分支 还记得前文写过的模板元编程…

WPF中的动画

WPF中的动画 周银辉动画无疑是WPF中最吸引人的特色之一&#xff0c;其可以像Flash一样平滑地播放并与程序逻辑进行很好的交互。这里我们讨论一下故事板。在WPF中我们采用Storyboard&#xf…