没有该部门的内容?
c++ - 何时将 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
只是额外的开销(假设传递给线程值的安全性不是有问题)并通过引用传递将是更好的解决方案。我错过了什么吗?
解决方案
推荐阅读
- mysql - 当我使用选择命令时如何添加每行的名称
- r - 使用 sapply 输出 R 中回归循环的所有回归系数?
- reactjs - 使用 React Spring 对 div 进行动画切换
- sql - 使用简体中文字符在 Azure SQL NVarchar 列中通过拼音搜索
- c# - ASP Dotnet Core MVC Docker 连接到 Postgresql
- rabbitmq - RabbitMq 中用于持久消息的后备存储是什么
- asp.net-mvc - 锁定对文件 MVC 的访问
- python - BeautifulSoup 输出作为
- terminal - 尝试在终端上执行 git pull 时,终端错误显示“错误:fetch 死于信号 9”
- python - 开始时没有 NaN 的滚动窗口