版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_38126105/article/details/85461013
在c++11中为我们提供了一种十分简易又遍历的异步线程的方法,这种就是async。以下是async的一些使用方法。分为以下几步:如何启动异步线程,如何知道异步线程的状态,怎么得到异步线程的结果。
#include "future"
#include "thread"
#include "iostream"
#include "windows.h"
using namespace std;
class A
{
public:
A() {}
void print(int a) { cout << a << endl; }
};
int main()
{
A a;
//std::future 的三种启动策略
//1.std::launch::deferred 当其他线程调用get来获取状态时,将调用非异步行为
//2.std::launch::async 保持异步行为,即传入的线程函数将在另一个线程中异步执行
//3.std::launch::deferred | std::launch::async,默认启动策略,他可以异步或着同步执行,取决与系统,不能自己控制
//推荐每次使用async时,都使用std::launch::async
//代码一
//std::future<int> result = async(std::launch::async, [&a](int i) {Sleep(10000); cout << i << endl; return i + 1; }, 5);
//std::future<int> result = async(std::launch::async, [&a](int i) {Sleep(10000); a.print(i); return i + 1; }, 5);
//cout << "hello" << endl;
//Sleep(10000);
//cout << "result" << result.get() << endl;
//std::future 获取状态的三种方式
//1.get 等待异步操作结束并返回结果,get只能调用一次,因为会使future失效,会启动没启动的线程
//2.wait 只是等待异步操作完成,没有返回值,会启动没启动的线程
//3.wait_for 超时等待返回结果。,不会启动没启动的线程
//所以需要得到返回结果的时候,只能使用get
//std::future 的三种状态
//1.std::future_status::deferred 异步操作还没开始
//2.std::future_status::ready 异步操作已经完成
//3.std::future_status::timeout 异步操作超时
//std::future<int> result = async(std::launch::async, [&a](int i) {Sleep(10000); a.print(i); return i + 1; }, 5);
//cout << "hello" << endl;
//std::future_status status;
//do
//{
// status = result.wait_for(std::chrono::seconds(1));
// if (std::future_status::deferred == status)
// {
// cout << "线程还未启动" << endl;
// }
// else if (std::future_status::ready == status)
// {
// cout << "线程已启动" << endl;
// }
// else
// {
// cout << "线程超时" << endl;
// }
//} while (std::future_status::ready != status);
//async获取线程结果的三种途径
//1.使用std::future ,通过get获取到返回的结果
//2.std::promise std::promise为获取线程函数中的某个值提供便利,
//在线程函数中给外面传进来的promise赋值,通过get_future获取的结果
//注意的是取值是间接的通过promise内部提供的future来获取的
//3.std::packaged_taskstd::packaged_task它包装了一个可调用的目标
//(如function, lambda expression, bind expression, or another function object)
//,以便异步调用,它和promise在某种程度上有点像,promise保存了一个共享状态的值,
//而packaged_task保存的是一个函数
//代码三
std::promise<int> pr;
async(std::launch::async, [](std::promise<int>& p) {p.set_value(10);}, std::ref(pr));
std::future<int> param = pr.get_future();
cout << "value is " << param.get() << endl;
std::packaged_task<int()> task([]() {return 8; });
async(std::launch::async, std::ref(task));
std::future<int> param2 = task.get_future();
cout << "task value is " << param2.get() << endl;
return 0;
}