通过直接函数调用将std::promise对象传递给函数。

问题描述 投票:2回答:1

我正在学习 std::promisestd::future 在C++中。我写了一个简单的程序来计算两个数的乘法。

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
1个回答
3
投票

当你编译这段代码时,即使不使用 std::thread 显式,您仍然必须添加 -pthread 命令行选项,因为在内部 std::promisestd::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 那么它应该抛出一些编译或链接错误,对吗?

非常好的问题。请看我的回答 此处.

© www.soinside.com 2019 - 2024. All rights reserved.