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

发布时间 2023-11-27 13:52:58作者: 左边的翼

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继续执行其他功能代码。