【发布时间】:2020-06-10 16:37:32
【问题描述】:
当我编写使用例如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++,它应该会引发链接错误。但它的编译没有任何错误,并且在运行时我遇到了上述问题。
【问题讨论】:
-
@TedLyngmo:他在问(认为需要很长时间才能明白这一点)为什么它会抛出异常而不是完全链接失败。
-
libstdc++ 有一个可插入的线程实现 (gthreads)。可插拔性在运行时处理。
-
好吧,我可以解释一下how,但我还是很高兴知道原因。
-
clang+++libc++works fine。libstdc++中的错误? -
@TedLyngmo,不是错误,而是实现细节。