首页 > 解决方案 > 通过直接函数调用将 std::promise 对象传递给函数

问题描述

我正在学习 C++ 中的std::promiseand 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。我在代码中遗漏了什么吗?

标签: c++pthreads

解决方案


当你编译这段代码时,即使不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::threadthen 它应该引发一些编译或链接错误,对吗?

非常好的问题。在这里查看我的答案。


推荐阅读