栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【C++11】promise和future介绍

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【C++11】promise和future介绍

【C++11】promise和future介绍
  • C++11提供了std::promise和std::future两个模板类,通过这两个模板类可以实现异步存储值并获取值的功能。
std::promise

The class template std::promise provides a facility to store a value or an exception that is later acquired asynchronously via a std::future object created by the std::promise object. Note that the std::promise object is meant to be used only once.

  • 模板类定义
emplate< class R > class promise;
template< class R > class promise;
template<>          class promise;
  • 成员函数
函数说明
构造函数-
析构函数-
operator=-
swap交换两个promise对象
get_future绑定并返回一个future对象
set_value设置值
set_value_at_thread_exit在线程退出时设置值
set_exception设置异常
set_exception_at_thread_exit在线程退出时设置异常
std::future

The class template std::future provides a mechanism to access the result of asynchronous operations

  • std::future可以被 std::async,std::packaged_task,std::promise创建,并用于异步获得 std::async,std::packaged_task,std::promise等对象设置的值或异常。
  • 模板类定义
template< class T > class future;
template< class T > class future;
template<>          class future;
  • 成员函数
函数说明
构造函数-
析构函数-
operator=-
get获取结果
validchecks if the future has a shared state
wait等待结果可用
wait_for等待结果可用(指定等待时间)
wait_until等待结果可用(指定等待时刻)
示例
#include 
#include 
#include 
#include 

int main()
{
    std::promise p;
    std::future f = p.get_future();
 
    std::thread t([&p]{
      p.set_value("lindduo");
    });
 
	std::string ret = f.get();
	std::cout << ret << std::endl;
    t.join();
    return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/889769.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号