std::future与std::promise在C++多线程同步与数据共享中的应用

1、std::promise与std::future

  std::promise与std::future通过配合使用完成数据的同步与共享,两者均是模板类;std::promise存储异步执行的值或异常;std::future提供可供访问的异步执行结果。二者配合使用伪码如下:

  std::promise<Type> pr;

  std::future<Type> fu(pr.get_future());

2、基础示例代码

复制代码
#include <iostream>
#include <thread>
#include <future>

void promise_string(std::promise<std::string> &pr)
{
    try
    {
        std::string str = __func__;
        pr.set_value(str);
    }
    catch (const std::exception& e)
    {
        pr.set_exception(std::current_exception());
    }
}

int main()
{
    std::promise<std::string> pr;
    std::future<std::string> fu(pr.get_future());
    std::thread tr(&promise_string, ref(pr));

    std::cout << "the current thread function name is:" << fu.get().c_str() << std::endl;
    tr.join();
    system("pause");
}
复制代码

   注意:上述代码中,fu.get()获取结果是阻塞的,在异步操作未执行完时,fu.get()将阻塞主线程直到异步操作完成。

3、不同线程间数据的传递

复制代码
#include <iostream>
#include <thread>
#include <future>

void promise_string(std::promise<std::string> &pr)
{
    try
    {
        for (int i = 0; i < 100; i++)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
            std::cout << "sleep" << std::endl;
        }
            
        std::string str = __func__;
        pr.set_value(str);
    }
    catch (const std::exception& e)
    {
        pr.set_exception(std::current_exception());
    }
}

void print_promise_info(std::future<std::string> &fu)
{
    std::cout << "the promise thread function name is: " << fu.get().c_str() << std::endl;
    std::cout << "the current thread function name is: " << __FUNCTION__ << std::endl;
}

int main()
{
    std::promise<std::string> pr;
    std::future<std::string> fu(pr.get_future());
    std::thread tr(&promise_string, ref(pr));
    std::thread trp(&print_promise_info,ref(fu));

    tr.detach();
    trp.detach();
    system("pause");
}
复制代码

   promise_string在一个线程tr中计算string值,trp线程启动并在fu.get()处阻塞直到线程tr执行完毕,线程tr执行完毕后,线程trp继续执行其他功能代码。

 

posted @   左边的翼  阅读(120)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示