如果不包含pthread,为什么GCC的线程标准库实现会引发异常?

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

[例如,当我编写使用std::promise的代码时,并且在GCC中不包含PThread库时,会引发异常,而不是链接器错误。例如:

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();
    product(std::move(prodPromise), a, b);
    std::cout << "20*10= " << prodResult.get() << std::endl;
}

如果我在没有-pthread的情况下编译此代码,则会引发以下异常:

terminate called after throwing an instance of 'std::system_error'
  what():  Unknown error -1
Aborted (core dumped)

如果std::promise在内部使用pthread库,则如果我不将-pthread命令行选项提供给g++,它应该会引发链接错误。但是它的编译没有任何错误,并且在运行时出现上述问题。

c++ pthreads c++14
1个回答
0
投票

原因是libstdc++使用了所谓的weak references

我们可以轻松地追踪为什么您的特定代码示例引发异常。 set_value()调用std::call_once。该函数在其实现中具有the line *

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