异步线程执行结果获取
std::future
std::future是一个类模板,经常被用于获取异步线程或者RPC远程调用的执行结果
就像这样:
std::future<int> m_future= AsyncCall(.....);
//AsyncCall是一个远程RPC调用函数
result = m_future.get();
//我们通过m_future的get函数的返回值即使调用结果
std::future::get
等待异步调用结束,并获取异步调用的返回值,在执行期间,线程会被阻塞住,直到异步调用的结果已经被std::promise设置好了,或者结束了之后才会解除阻塞状态。
必须强调的是,在调用这个函数前,std::future必须已经跟 std::promise, std::async, std::packaged_task等进行绑定,否则调用get函数会出现异常
std::future::wait
等待异步调用结束,但是并不获取异步调用的返回值,其余均与std::future::get一致
这里看不懂没关系,下面有简单的实际使用案例:
std::promise
使用示例:
#include <iostream>
#include <future>
#include <thread>
#include <time.h>
#include <chrono>
int main()
{
std::promise<int> prom;
std::future<int> m_future = prom.get_future();
std::thre