std::async
来自cppreference.com
![]() |
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
定义于头文件 <future>
|
||
template< class Function, class... Args> std::future<typename std::result_of<Function(Args...)>::type> |
(1) | (C++11 起) |
template< class Function, class... Args > std::future<typename std::result_of<Function(Args...)>::type> |
(2) | (C++11 起) |
模板函数
async
异步地执行的函数f
(可能在一个单独的线程中),并最终返回一个包含函数调用结果的std::future。- 1) 行为和async(std::launch::async | std::launch::deferred, f, args...)一样。换句话说,
f
既可以在一个新的线程中被异步地执行,也可以在请求std::future的结果时被同步地调用。原文:Behaves the same as async(std::launch::async | std::launch::deferred, f, args...). In other words,f
may be started in a new thread or it may be run synchronously when the resulting std::future is queried for a value.
- 如果设置了“异步”的标志(即policy & std::launch::async != 0),则
async
产生一个新的线程执行,就像由std::thread(f, args...)执行一样,但如果函数f
有返回值或会抛出异常,它被存储在共享访问状态中,通过async
返回给调用者的std::future。原文:If the async flag is set (i.e. policy & std::launch::async != 0), thenasync
spawns a new thread of execution as if by std::thread(f, args...), except that if the functionf
returns a value or throws an exception, it is stored in the shared state accessible through the std::future thatasync
returns to the caller.
- 如果设置了“递延”标志(即policy & std::launch::deferred != 0),则
async
像std::thread构造函数一样传递args...
,但不会产生一个新的线程执行。相反,进行了“延迟求值”:一个async
返回给调用者的std::future上的没等待时间的函数的第一次调用,会导致f(args...)
在当前线程中被执行。其他所有对相同的std::future的访问将立即返回结果。原文:If the deferred flag is set (i.e. policy & std::launch::deferred != 0), thenasync
convertsargs...
the same way as by std::thread constructor, but does not spawn a new thread of execution. Instead, lazy evaluation is performed: the first call to a non-timed wait function on the std::future thatasync
returned to the caller will causef(args...)
to be executed in the current thread. All further accesses to the same std::future will return the result immediately.
目录 |
[编辑] 参数
f | - | |||||||||||||||||
args... | - | |||||||||||||||||
policy | - | 位掩码值,其中个别的位控制在允许的执行方法
原文: bitmask value, where individual bits control the allowed methods of execution
|
[编辑] 返回值
std::future指的是该函数的返回值。
[编辑] 异常
如果执行标志是std::launch::async并且依据实现无法创建新的线程,则抛出带错误原因std::errc::resource_unavailable_try_again的std::system_error。
[编辑] 注释
实现可以通过设置默认执行策略中的额外的(实现定义的)标志位,来扩展第一个std::async重载的行为。
[编辑] 示例
运行此代码
#include <iostream> #include <vector> #include <algorithm> #include <numeric> #include <future> template <typename RAIter> int parallel_sum(RAIter beg, RAIter end) { typename RAIter::difference_type len = end-beg; if(len < 1000) return std::accumulate(beg, end, 0); RAIter mid = beg + len/2; auto handle = std::async(std::launch::async, parallel_sum<RAIter>, mid, end); int sum = parallel_sum(beg, mid); return sum + handle.get(); } int main() { std::vector<int> v(10000, 1); std::cout << "The sum is " << parallel_sum(v.begin(), v.end()) << '\n'; }
输出:
The sum is 10000