问题
I am learning the std::promise
and std::future
in C++. I wrote one simple program to calculate the multiplication of two numbers.
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();
}
In the above code if I invoke the product
function using threads it's working fine. But if I invoke the function using direct function call I am getting the following error:
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1
Aborted (core dumped)
I added some logs to check the problem. I am getting the error while setting the value (set_value
) in the function product
. Is there anything I missed in the code?
回答1:
When you compile this code, even if don't use std::thread
explicitly, you still have to add -pthread
command line option, because internally std::promise
and std::future
depend on the pthread
library.
Without -pthread
on my machine I get:
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1
With -pthread
:
20*10 = 200
My doubt is if
std::promise
usingstd::thread
then it should throw some compilation or linkage error right?
Very good question. See my answer here.
来源:https://stackoverflow.com/questions/62307634/passing-stdpromise-object-to-a-function-via-direct-function-call