有以下几种形式
//从c++11到c++17有
template< class Function, class... Args >
std::future<typename std::result_of<typename std::decay<Function>::type(typename std::decay<Args>::type...)>::type>
async( Function&& f, Args&&... args );
template< class Function, class... Args >
std::future<typename std::result_of<typename std::decay<Function>::type(
typename std::decay<Args>::type...)>::type>
async( std::launch policy, Function&& f, Args&&... args );
//从c++17到c++20有
template< class Function, class... Args >
std::future<std::invoke_result_t<std::decay_t<Function>,
std::decay_t<Args>...>>
async( Function&& f, Args&&... args );
template< class Function, class... Args >
std::future<std::invoke_result_t<std::decay_t<Function>,
std::decay_t<Args>...>>
async( std::launch policy, Function&& f, Args&&... args );
//从c++20有
template< class Function, class... Args >
[[nodiscard]] std::future<std::invoke_result_t<std::decay_t<Function>, std::decay_t<Args>...>>
async( Function&& f, Args&&... args );
template< class Function, class... Args >
[[nodiscard]] std::future<std::invoke_result_t<std::decay_t<Function>, std::decay_t<Args>...>>
async( std::launch policy, Function&& f, Args&&... args );
上面policy参数支持的值有
std::launch::async:异步调用,与调用线程是不同的线程
std::launch::deferred:延时计算,在调用的线程内
在不带launch类型参数时,默认是异步调用 的
代码样例
#include <algorithm>
#include <future>
#include <iostream>
#include <mutex>
#include <numeric>
#include <string>
#include <vector>
#include <thread>
using namespace std;
mutex m;
struct X
{
void foo(int i, const string& str)
{
lock_guard<mutex> lk(m);
cout << "foo cur thread id :" << this_thread::get_id() << endl;
cout << str << ' ' << i << '\n';
}
void bar(const string& str)
{
lock_guard<mutex> lk(m);
cout << "bar cur thread id :" << this_thread::get_id() << endl;
cout << str << '\n';
}
int operator()(int i)
{
lock_guard<mutex> lk(m);
cout << "operator cur thread id :" << this_thread::get_id() << endl;
cout << i << '\n';
return i + 10;
}
};
int main()
{
X x;
cout << "main thread id :" << this_thread::get_id() << endl;
auto a1 = async(&X::foo, &x, 42, "Hello");
auto a2 = async(launch::deferred, &X::bar, x, "world!");
auto a3 = async(launch::async, X(), 43);
a2.wait();
cout << a3.get() << '\n';
}
输出为
可以看到a1,a3和主线程不同
a2与主线程id一致