zoukankan      html  css  js  c++  java
  • c++11 异步编程 std::async

    知识点

    std::future 获取异步函数调用的结果。
    std::result_of 获取函数模板的返回类型。
    std::async 用于创建异步任务,实际上就是创建一个线程执行相应任
    std::launch::async, enable asynchronous evaluation 异步执行
    std::launch::deferred, enable lazy evaluation 懒汉模式,获取结果时才执行(当调用get时,async才执行)
    typename &&f 非模板参数里表示右值引用,模板参数中表示universal references 万能引用。
    std::forward 完美转发 std::forward<T>()不仅可以保持左值或者右值不变,同时还可以保持const、Lreference、Rreference、validate等属性不变
    #include <iostream>
    #include <future>
    #include <string>
    #include <mutex>
    template <typename F, typename... Args>
    
    static auto Async(F&& f, Args&&... args)
        -> std::future<typename std::result_of<F(Args...)>::type> {
      return std::async(
                       std::launch::async,
                       std::bind(std::forward<F>(f), std::forward<Args>(args)...);
    }
    
    int main(int argc, const char **argv) {
     
        auto my_callback = [](){
            std::cout << "This is test example" << std::endl;
        };
        
        auto* callback =
        reinterpret_cast<std::function<void()>*>(&(my_callback));
            Async([this, callback] {
              if (true) {
                (*callback)();
              }        
            });
        return 0;
    
    }
  • 相关阅读:
    Acwing 284.金字塔 (区间DP)
    Acwing 283.多边形 (区间DP)
    Acwing 277.饼干 (DP+排序不等式)
    Acwing 274.移动服务 (DP)
    Acwing 273.分级 (DP)
    Acwing 271.杨老师的照相排序 (DP)
    Acwing 272.最长公共上升子序列 (DP)
    Mybatis-缓存
    mybatis与spring整合
    mybatis-sql映射文件
  • 原文地址:https://www.cnblogs.com/rayfloyd/p/14306719.html
Copyright © 2011-2022 走看看