通过直接函数调用将 std::promise 对象传递给函数
Passing std::promise object to a function via direct function call
我正在学习 C++ 中的 std::promise
和 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)
我添加了一些日志来检查问题。在函数 product
中设置值 (set_value
) 时出现错误。我在代码中遗漏了什么吗?
当你编译这段代码时,即使不显式使用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
My doubt is if std::promise
using std::thread
then it should throw some compilation or linkage error right?
很好的问题。看我的回答.
我正在学习 C++ 中的 std::promise
和 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)
我添加了一些日志来检查问题。在函数 product
中设置值 (set_value
) 时出现错误。我在代码中遗漏了什么吗?
当你编译这段代码时,即使不显式使用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
My doubt is if
std::promise
usingstd::thread
then it should throw some compilation or linkage error right?
很好的问题。看我的回答