C++11 future async异步调用函数 基础用法了解

/*解决主线程和子线程后期同步的问题 类似于windows中的事件*/
#include "iostream"
#include "future"
#include "thread"

using namespace  std;

int main(void)
{
    promise<int>proms;//构建一个承若
    auto& fut = proms.get_future();//用自动变量接收这个承诺
    
    thread t1([&fut/*捕获承诺*/](void)->void
    {
        wcout << "doing  sth.........." << endl;
        wcout << "waiting for food" << endl;
        wcout << "got " << fut.get()/*等待食物,此刻子线程阻塞在这里*/ << "food" << endl;

   
    });

    this_thread::sleep_for(chrono::seconds(10));//主线程暂时休眠10s
    proms.set_value(100);//主线程提供食物,子线程接着运行,不然子线程在上面的fut等待
    t1.join();//主线程等待子线程一起结束,子线程不结束主线程不结束
    wcout << "fnish" << endl;
    return 0;
}

//--------------------------------------------------------async 异步调用函数 封装了复杂的c++线程创建等细节--------------------------------------
#include<iostream>
#include<future>   //C11新特性

using namespace std;
 
int bar(int num)
{
    for (int i = 0; i < num; ++i)
    {
        this_thread::sleep_for(chrono::microseconds(1000));
        cout << "X" << endl;
    }
    return 1;
}

int main(void)
{
    cout << "main thread begin to exute" << endl;
    future<int>fut = async(bar, 10);  //作为函数bar的入参  通过函数的返回,作为同步点 
    cout << "sub thread begin to exute" << endl;
    int result = fut.get();           //子线程 主线程同步 子线程没执行完,主线程会在这里等
    cout << "got fut:" <<result<< endl;
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中的异步调用可以使用std::async函数来实现。std::async函数返回一个std::future对象,该对象可以用于获取异步操作的结果。std::async函数有两个参数,第一个参数是std::launch枚举类型,用于指定异步操作的启动方式,可以是std::launch::async表示异步启动,也可以是std::launch::deferred表示延迟启动;第二个参数是一个可调用对象,可以是函数指针、函数对象或者Lambda表达式等。当使用std::launch::async启动异步操作时,std::async函数会在新线程中执行该可调用对象;当使用std::launch::deferred启动异步操作时,std::async函数会在调用get()函数时执行该可调用对象。 下面是一个示例程序,展示了std::async函数的使用方法和异步启动和延迟启动的区别: ``` #include <chrono> #include <future> #include <iostream> int main() { auto begin = std::chrono::system_clock::now(); auto asyncLazy = std::async(std::launch::deferred, [] { return std::chrono::system_clock::now(); }); auto asyncEager = std::async(std::launch::async, [] { return std::chrono::system_clock::now(); }); std::this_thread::sleep_for(std::chrono::seconds(1)); auto lazyStart = asyncLazy.get() - begin; auto eagerStart = asyncEager.get() - begin; auto lazyDuration = std::chrono::duration<double>(lazyStart).count(); auto eagerDuration = std::chrono::duration<double>(eagerStart).count(); std::cout << "asyncLazy evaluated after : " << lazyDuration << " seconds." << std::endl; std::cout << "asyncEager evaluated after: " << eagerDuration << " seconds." << std::endl; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值