Passing std::promise object to a function via direct function call

我是研究僧i 提交于 2020-06-16 02:59:50

问题


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 using std::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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!