首页 > 解决方案 > 何时将 std::future 和 std::promise 与 std::thread 一起使用

问题描述

因此,当我需要在没有 OOP 的情况下从线程返回值时,主要选项是通过引用传递函数参数并使用 promise-future 机制。

#include <iostream>
#include <thread>
#include <future>

void dbl(std::promise<int>&& pr, int x)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));  // (1)simulating some work
    pr.set_value(x*x);
    std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // (2)continuing doing some work
}

void dbl1(int& x)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));  // simulating some work
    x *= x;
}

int main()
{
  std::promise<int> pr;
  auto fut = pr.get_future();

  std::thread t(dbl, std::move(pr), 5);
  int d = fut.get(); //we are waiting for the result to be ready
  std::cout<<d<<std::endl;  

  std::thread t1(dbl1, std::ref(d));
  t1.join(); //and here we are waiting for the result to be ready
  std::cout<<d<<std::endl;  

  t.join();  //to avoid program abortion in the end      
}

因此,正如我所看到的,如果我需要的结果是线程将做的最后或唯一的事情,我并不真正需要promise-future,因为只是传递引用将是完全一样的,尽管我需要更加小心不要更改主线程或其他线程中的值。

因此,dbl在获得x价值后,我需要做更多的事情,promise-future因为我已经可以将计算值传递给主线程,因此我可以从中受益,但这dbl1 promise-future 只是额外的开销(假设传递给线程值的安全性不是有问题)并通过引用传递将是更好的解决方案。我错过了什么吗?

标签: c++multithreadingc++11

解决方案


推荐阅读