什么是异步?
async的两种方式
//方式1
async( Function&& f, Args&&... args );
//方式2
async( std::launch policy, Function&& f, Args&&... args );
函数参数:
f:任务函数
Args:传递给f的参数
policy:可调用对象f的执行策略
策略 | 说明 |
---|---|
std::launch::async | 调用async函数时创建新的线程执行任务函数 |
std::launch::deferred | 调用async函数时不执行任务函数,直到调用了future的get()或者wait()时才执行任务(这种不会创建新的线程) |
方式1
#include <iostream>
#include <thread>
#include <future>
using namespace std;
int main()
{
cout << "主线程ID: " << this_thread::get_id() << endl;
// 调用函数直接创建线程执行任务
future<int> f = async([](int x) {
cout << "子线程ID: " << this_thread::get_id() << endl;
this_thread::sleep_for(chrono::seconds(5));
return x += 100;
}, 100);
future_status status;
do {
status = f.wait_for(chrono::seconds(1));
if (status == future_status::deferred)
{
cout << "线程还没有执行..." << endl;
f.wait();
}
else if (status == future_status::ready)
{
cout << "子线程返回值: " << f.get() << endl;
}
else if (status == future_status::timeout)
{
cout << "任务还未执行完毕, 继续等待..." << endl;
}
} while (status != future_status::ready);
return 0;
}
方式2
std::launch::async 策略
#include <iostream>
#include <thread>
#include <future>
using namespace std;
int main()
{
cout << "主线程ID: " << this_thread::get_id() << endl;
// 调用函数直接创建线程执行任务
future<int> f = async(launch::async, [](int x) {
cout << "子线程ID: " << this_thread::get_id() << endl;
return x += 100;
}, 100);
this_thread::sleep_for(chrono::seconds(2));
cout << f.get();
return 0;
}
std::launch::deferred策略
#include <iostream>
#include <thread>
#include <future>
using namespace std;
int main()
{
cout << "主线程ID: " << this_thread::get_id() << endl;
// 调用函数直接创建线程执行任务
future<int> f = async(launch::deferred, [](int x) {
cout << "子线程ID: " << this_thread::get_id() << endl;
return x += 100;
}, 100);
this_thread::sleep_for(chrono::seconds(2));
cout << f.get();
return 0;
}
这里可以看到主子线程ID一样,是因为这个策略下,不创建子线程,函数还是在主线程里面执行的。