• 感谢大家访问本站,希望本站的内容可以帮助到大家!

  • 计算机图形学与计算几何经典必备书单整理,下载链接可参考:https://www.stubbornhuang.com/1256/

  • 本站由于前段时间遭受到大量临时和国外邮箱注册,所以对可注册的邮箱类型进行了限制!

  • 如果觉得本站的内容有帮助,可以考虑打赏博主哦!

  • 问题反馈可发送邮件到stubbornhuang@qq.com

  • 本站会放置Google广告用于维持域名以及网站服务器费用。

  • 工资「喂饱肚子」,副业「养活灵魂」!

  • 欢迎大家交换友链,可在https://www.stubbornhuang.com/申请友情链接进行友链交换申请!

  • 在本站开通年度VIP,无限制下载本站资源和阅读本站文章

C++ – 详解std::promise

C++ 发布于2024-01-15 阅读 1,193次 0次评论 0次点赞 本文共1027个字,阅读需要3分钟。

1 详解std::promise

std::promise提供了在异步线程函数中存储值并在当前线程获取值的机制,为获取某个线程函数中的值提供了便利的方法。

原型

template< class R > class promise;
template< class R > class promise<R&>;
template<> class promise<void>;

成员函数

  • set_value:为std::promise设置指定的值
  • set_value_at_thread_exit:为std::promise设置指定的值,但是仅在退出线程时进行通知
  • set_exception:为std::promise设置指定的异常
  • set_exception_at_thread_exit:为std::promise设置指定的异常,但是仅在退出线程时进行通知
  • get_future:获取与std::promise相关联的std::future

2 std::promise使用

下面是std::promise的使用示例,在以下代码中,在主线程中另起了一个子线程用于计算1-1000数的总和,我们将std::promise传递到子线程函数sum,并在计算结果之后将结果设置给std::promise,然后在主线程中使用get_future获取std::promisestd::future,然后通过std::future获取结果。

#include <iostream>
#include <future>

void sum(int start, int end, std::promise<int> promise)
{
    int sum = 0;
    for (int i = start; i < end; ++i)
    {
        sum += i;
    }
    promise.set_value(sum);
}

int main()
{
    int start = 0;
    int end = 1000;

    std::promise<int> temp_promise;
    std::future<int> res = temp_promise.get_future();
    std::thread sum_thread(sum, 1, 1000, std::move(temp_promise));

    std::cout << "result1 = " << res.get() << std::endl;

    sum_thread.join();

    return 0;
}

参考

欢迎扫码关注我的微信公众号,及时获取文章更新

微信公众号二维码

本文作者:StubbornHuang

版权声明:本文为站长原创文章,如果转载请注明原文链接!

原文标题:C++ – 详解std::promise

原文链接:https://www.stubbornhuang.com/2954/

发布于:2024年01月15日 17:46:16

修改于:2024年01月16日 11:13:03

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

文章末尾
上一篇
C++ - 详解std::future
C++
下一篇
C++中的中文字符编码
C++
当前分类随机文章推荐

发表评论

您必须 [ 登录 ] 才能发表留言!

关注我们的公众号

微信公众号