背景

  • C++11添加了thread,可以通过std::thread({})方便的创建线程
  • thread不能方便的获取线程运行结果

用法

  • 返回值为std::future(下面会讲到),第一个参数policy,第二个参数为function,可以是lamda

    template< class Function, class... Args >
    std::future<std::invoke_result_t<std::decay_t, std::decay_t...>>
        async( std::launch policy, Function&& f, Args&&... args);
  • 关于policy

    • std::launch::async  新建线程,异步执行
    • std::launch::deferred 当前线程,调用特定函数时,同步执行
    • std::launch::async | std::launch::deferred  取决于实现,不得而知
    • NULL 取决于实现,不得而知

detail

  • std::launch::async 理论上会新建线程异步执行task,std::launch::deferred 只会在当前线程执行

    int main() {
      	std::cout << std::this_thread::get_id() <<std::endl;
        std::vector<std::future> futures;
        for (int i = 0; i < 25; ++i) {
            // 当policy为std::launch::deferred时,可以看到所有thread id都是主线程id
            // 当policy为std::launch::async时,可以看到所有thread id各不相同
            auto fut = std::async(std::launch::deferred, [] {          
                std::cout << std::this_thread::get_id() <<std::endl;
            });
            futures.push_back(std::move(fut));
        }
        std::for_each(futures.begin(), futures.end(), [](std::future& fut) {
            fut.wait();
        });
    }
  • policy为async时,如果没有获取结果,会单线程同步执行task

    int main() {
      std::cout << std::this_thread::get_id() <<std::endl;
      // 会在主线程外新建一个线程,去同步顺序执行下面两个task,可以看到thread id相同
      std::async(std::launch::async, []() {
      // 如果上一行替换成 auto f = std::async(std::launch::async, []() {
      // 会新建两个线程,并行执行两个task
        std::cout << std::this_thread::get_id() <<std::endl;
      });
      std::async(std::launch::async, []() {
        std::cout << std::this_thread::get_id() <<std::endl;
      });
    }
  • 由于async采用async policy时,本质上还是新建一个线程

    所以不适合轻量task,线程的创建和销毁开销可能更大

    这里未来应该支持线程池