6.std::thread & std::async

线程 std::thread std::async std::future

std::thread

c++11 的线程创建

void f(int n);
std::thread t(f, n + 1);
t.join();
void foo(bool clause) { /* do something... */ }

std::vector<std::thread> threadsVector;
threadsVector.emplace_back([]() {
  // Lambda function that will be invoked    
});
threadsVector.emplace_back(foo, true);  // thread will run foo(true)
for (auto& thread : threadsVector) {
  thread.join(); // Wait for threads to finish
}

std::async

  • 标准异步库,通过这个异步接口可以很方便的获取线程函数的执行结果。std::async会自动创建一个线程去调用线程函数,它返回一个std::future,这个future中存储了线程函数返回的结果,当我们需要线程函数的结果时,直接从future中获取。

  • 还提供了线程的创建策略,可以通过延迟加载的方式去创建线程。

  1. std::launch::async | std::launch::deferred It is up to the implementation whether to perform asynchronous execution or lazy evaluation.

  2. std::launch::async Run the callable object on a new thread.

  3. std::launch::deferred Perform lazy evaluation on the current thread.

  • std::async 实际是对 std::future、std::promise和std::packaged_task 的封装

std::future

std::future提供了一种访问异步操作结果的机制

可以通过查询future的状态(future_status)来获取异步操作的结果。future_status有三种状态:

  • deferred:异步操作还没开始

  • ready:异步操作已经完成

  • timeout:异步操作超时

查询future状态例子如下:

获取future结果有三种方式:

get、wait、wait_for

  • get等待异步操作结束并返回结果

  • wait只是等待异步操作完成,没有返回值

  • wait_for是超时等待返回结果。

std::promise

std::promise为获取线程函数中的某个值提供便利,在线程函数中给外面传进来的promise赋值,当线程函数执行完成之后就可以通过promis获取该值了,值得注意的是取值是间接的通过promise内部提供的future来获取的

std::packaged_task

std::packaged_task它包装了一个可调用的目标(如function, lambda expression, bind expression, or another function object),以便异步调用,它和promise在某种程度上有点像,promise保存了一个共享状态的值,而packaged_task保存的是一个函数

最后更新于

这有帮助吗?