c++ - 通过直接函数调用将 std::promise 对象传递给函数
问题描述
我正在学习 C++ 中的std::promise
and std::future
。我写了一个简单的程序来计算两个数字的乘积。
void product(std::promise<int> intPromise, int a, int b)
{
intPromise.set_value(a * b);
}
int main()
{
int a = 20;
int b = 10;
std::promise<int> prodPromise;
std::future<int> prodResult = prodPromise.get_future();
// std::thread t{product, std::move(prodPromise), a, b};
product(std::move(prodPromise), a, b);
std::cout << "20*10= " << prodResult.get() << std::endl;
// t.join();
}
在上面的代码中,如果我product
使用线程调用函数,它工作正常。但是,如果我使用直接函数调用来调用该函数,则会收到以下错误:
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1
Aborted (core dumped)
我添加了一些日志来检查问题。set_value
在函数中设置值 ()时出现错误product
。我在代码中遗漏了什么吗?
解决方案
当你编译这段代码时,即使不std::thread
显式使用,你仍然必须添加-pthread
命令行选项,因为在内部std::promise
并且std::future
依赖于pthread
库。
没有-pthread
在我的机器上,我得到:
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1
与-pthread
:
20*10 = 200
我的疑问是,如果
std::promise
使用std::thread
then 它应该引发一些编译或链接错误,对吗?
非常好的问题。在这里查看我的答案。
推荐阅读
- javascript - 为什么 .get() 在我的不和谐机器人代码中不起作用?
- ios - 如何使用 scrollViewWillEndDragging:withVelocity:targetContentOffset 确保仅在两个可能的位置停止滚动?
- android - 反应原生:无法更改包名称 - 总是失败
- python - 在while循环中嵌套if/else语句
- javascript - JS DOM insertBefore() 无法正常工作
- android - 如何删除列间距交错网格视图
- linux - Logging Linux Terminal Output to Files by Date?
- javascript - 创建多个画布模式失败
- azure - Azure B2C ADFS autologin logout failed
- html - 如何构建html时事通讯响应块顺序