福田网站建设流程网站设计网页配色
news/
2025/9/23 9:21:09/
文章来源:
福田网站建设流程,网站设计网页配色,广州少儿编程培训机构,红酒商城网站建设方案书std::future —C17 多线程
std::future
C标准程序库使用future来模拟这类一次性事件#xff1a;若线程需等待某个特定的一次性事件发生#xff0c;则会以恰当的方式取得一个future#xff0c;它代表目标事件#xff1b;接着#xff0c;该线程就能一边执行其他任务#…std::future —C17 多线程
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::futurestd::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 f1std::async(X::foo,x,42,hello); ⇽--- ①调用p-foo(42,hello)其中p的值是x即x的地址
auto f2std::async(X::bar,x,goodbye); ⇽--- ②调用tmpx.bar(goodbye)其中tmpx是x的副本
struct Y
{double operator()(double);
};
Y y;
auto f3std::async(Y(),3.141); ⇽--- ③调用tmpy(3.141)。其中由Y()生成一个匿名变量传递给std::async()进而发生移动构造。在std::async()内部产生对象tmpy在tmpy上执行Y::operator()(3.141)
auto f4std::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 f5std::async(move_only()); ⇽--- ⑥调用tmp()其中tmp等价于std::move (move_only())它的产生过程与③相似按默认情况下std::async()的具体实现会自行决定——等待future时是启动新线程还是同步执行任务。大多数情况下我们正希望如此。不过我们还能够给std::async()补充一个参数以指定采用哪种运行方式。参数的类型是std::launch其值可以是std::launch::deferred或std::launch::async。前者指定在当前线程上延后调用任务函数等到在future上调用了wait()或get()任务函数才会执行后者指定必须另外开启专属的线程在其上运行任务函数。该参数的值还可以是std::launch::deferred | std::launch:: async表示由std::async()的实现自行选择运行方式。最后这项是参数的默认值。若延后调用任务函数则任务函数有可能永远不会运行。举例如下。
auto f6std::async(std::launch::async,Y(),1.2); ⇽--- ①运行新线程auto f7std::async(std::launch::deferred,baz,std::ref(x)); ⇽--- ②在wait()或get()内部运行任务函数
auto f8std::async( ⇽--- std::launch::deferred | std::launch::async,baz,std::ref(x));
auto f9std::async(baz,std::ref(x)); ⇽--- ③交由实现自行选择运行方式
f7.wait(); ⇽--- ④前面②处的任务函数调用被延后到这里才运行
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/912029.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!