promise 和future多线程异步传值
promise用于异步传输变量
std::promise提供存储异步通信的值,再通过其对象创建的std::future异步获得结果。
std::promise只能使用一次。void set_value(_Ty&& _Val)设置传递值,只能调用一次
std::future提供访问异步操作结果的机制
get()阻塞等待promise set_value的值
代码演示
/*
C++ 11
promise与future
*/
#include <thread>
#include <iostream>
#include <future>
#include <string>
using namespace std;
void TestFuture(promise<string>p)
{
this_thread::sleep_for(3s);
cout << "Begin set value" << endl;
p.set_value("TestFuture value");
this_thread::sleep_for(3s);
cout << "end TestFutrue" << endl;
}
int main()
{
//异步传输变量存储
promise<string>p;
//用来获取线程异步值获取
auto future = p.get_future();
auto th = thread(TestFuture, move(p));
cout << "begin future.get()" << endl;
cout << "future_get() = " << future.get() << endl;
cout << "end future.get()" << endl;
th.join();
//getchar();
printf("All done!\n");
return 0;
}
packaged_task 异步调用函数打包,超时判断
ackaged_task包装函数为一个对象,用于异步调用,其返回值能通过std::future对象访问
与bind的区别,可以不调用,函数访问和获取返回值分开调用
下面代码中还包含了是否超时判断
#include <thread>
#include<iostream>
#include<future>
#include <string>
using namespace std;
string TestPack(int index)
{
cout << "begin Test Pack " <<index<< endl;
this_thread::sleep_for(2s);
return "Test Pack return ";
}
int main()
{
packaged_task<string(int)>task(TestPack);
auto result = task.get_future();//result结果与TestPack函数返回值类型一致
//task(100);//直接设置值
thread th(move(task),101);//通过线程异步传值
cout << "begin result get()" << endl;
//测试是否超时判断
//for (int i = 0; i < 8; i++)//该设置模拟超时
for (int i = 0; i < 30; i++)//该设置可以出来结果
{//判断是否准备状态
if (result.wait_for(100ms) != future_status::ready)
{
continue;
}
}
if (result.wait_for(100ms) == future_status::timeout)
{//判断是否超时,提示或者获取值
cout << "wait result timeout " << endl;
}
else
{
cout << "result get " << result.get() << endl;
}
th.join();
printf("End All!\n");
getchar();
return 0;
}
async 异步运行,返回保有其结果的std::future
C++11 异步运行一个函数,并返回保有其结果的std::future
launch::deferred 延迟执行在调用wait和get时,调用函数代码;
launch::async创建线程(默认)
返回的线程函数的返回值类型的std::future<int> (std::future<线程函数的返回值类型>)
re.get()获取结果,会阻塞等待
代码中测试了async 不创建线程和创建另一个线程进行异步执行的演示代码:
#include <thread>
#include<iostream>
#include<future>
#include <string>
using namespace std;
string TestAsync(int index)
{
cout << index<<" begin in TestAsync, TestAsync thread id: " << this_thread::get_id() << endl;//如果该线程号和主函数ID号一致,则说明是在一个线程中
this_thread::sleep_for(2s);
return "TestAsync string return ";
}
int main()
{
cout << "main thread id " << this_thread::get_id() << endl;//
//不创建线程启动异步任务
auto future = async(launch::deferred,TestAsync,100);
this_thread::sleep_for(100ms);//等待100ms,确认是不是操作步骤导致get函数
cout << "begin future get " << endl;
cout << "future.get() = " << future.get() << endl;
cout << "end future get" << endl;
//创建异步线程方式进行异步任务
printf("=============创建异步线程=======================\n");
auto future2 = async(TestAsync, 101);
this_thread::sleep_for(100ms);
cout << "begin future2 get " << endl;
cout << "future2.get() = " << future2.get() << endl;
cout << "end future2 get" << endl;
printf("End All!\n");
getchar();
return 0;
}