C++线程编程-future和async

future

使用future等待一次性事件,它和async连用。

async

异步运行一个函数,可能在新的线程中。

// 使用futer等待一次性事件
// 使用async 启动异步任务并返回结果
#include <future>
#include <iostream>
#include <string>
#include <functional>
using namespace std;


int find_thr_answer_to_ltuae(int a)
{
    this_thread::sleep_for(5s);
    a++;
    return a;
}
void do_other_stuff()
{
    cout << "do something" << endl;
}

/* 使用async来讲参数传递给函数 */
struct X
{
    void foo(int,const string&);
    string bar(const string&);
};
X x;
// 调用p->foo(42,"hello") , p是&x
future<void> f1 = std::async(&X::foo,&x,42,"hello");
// 调用temp.bar("goodbye"),temp是x的副本
auto f2 = std::async(&X::bar,x,"goodbye");

struct Y
{
    double operator()(double);
};
Y y;
// 调用temp(3.14),其中temp是从Y()移动构造的
auto f3 = std::async(Y(),3.14);
// 调用y(3.14);
auto f4 = std::async(ref(y),3.14);

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()();
};
// 调用tmp(),其中temp是从std::moev(move_only())构造的
auto f5 = std::async(move_only());

// 函数声明
X baz(X&);
// 调用baz(x)
std::async(baz,ref(x));

/* async调用函数的方式 */
// 1.std::launch::deferred 函数的调用会延迟,直到调用future.wait或者get
// 2.std::launch::async,启动单独的线程运行函数
// 3.std::launch::async | std::launch::deferred 默认,由具体实现来选择
auto f6 = async(std::launch::deferred,Y(),1.2);


int main()
{
    future<int> answer = async(find_thr_answer_to_ltuae,1);
    do_other_stuff();
    cout << "answer is " << answer.get() << endl;
    exit(0);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

橙子砰砰枪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值