c++ - std::call_once 抛出 std::system_error(未知错误 -1)

标签 c++ linux gcc

我正在使用 C++ OpenCL 包装器,我想知道为什么我的程序会崩溃。我发现对 std::call_once 的任何调用都会引发错误。

#include <mutex>

int main() {
    static std::once_flag f;
    std::call_once(f, []{});
}

程序输出:

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

这是 g++ -v 的输出:

Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-pc-linux-gnu/8.1.1/lto-wrapper
Target: x86_64-pc-linux-gnu
Configured with: /build/gcc/src/gcc/configure --prefix=/usr --libdir=/usr/lib --libexecdir=/usr/lib --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=https://bugs.archlinux.org/ --enable-languages=c,c++,ada,fortran,go,lto,objc,obj-c++ --enable-shared --enable-threads=posix --enable-libmpx --with-system-zlib --with-isl --enable-__cxa_atexit --disable-libunwind-exceptions --enable-clocale=gnu --disable-libstdcxx-pch --disable-libssp --enable-gnu-unique-object --enable-linker-build-id --enable-lto --enable-plugin --enable-install-libiberty --with-linker-hash-style=gnu --enable-gnu-indirect-function --enable-multilib --disable-werror --enable-checking=release --enable-default-pie --enable-default-ssp
Thread model: posix
gcc version 8.1.1 20180531 (GCC)

最佳答案

如Praetorian 的评论所述,std::call_once 需要调用系统线程库。更具体地说,它将调用 __gthread_once。如果可执行文件未链接到 pthread,该函数将返回 -1,然后引发异常。

要使程序启用 pthread -pthread 选项需要同时传递给编译器和链接器,如 gcc documentation 中所述.有时仅与 -lpthread 链接 is not enoughnot just because of additional macros .对于 CMake 用户,有一个开箱即用的模块可以帮助添加对 pthread(或任何系统线程库)的支持,可以像这样使用:

find_package(Threads REQUIRED)
target_link_libraries(myTarget PRIVATE Threads::Threads)

如有必要,这将添加任何必需的编译和链接标志。

关于c++ - std::call_once 抛出 std::system_error(未知错误 -1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51584960/

相关文章:

linux - 使用防火墙禁用 mysql 访问

c++ - C++ 编译器何时会为方法推断出 noexcept?

c++ - 拒绝访问 NT AUTHORITY\LOCAL SERVICE

c++ - _GLIBCXX_USE_CXX11_ABI、GCC 4.8 和 ABI 兼容性

c++ - 在成员初始化器列表中分配unique_ptr

linux - Qt C++项目在另一台PC上

c++ - 任何方法都可以使子字符串的解析和匹配比默认解析和匹配更快

linux - 如何跟踪锁定 unix 帐户的进程

c - c程序内存错误

linux - SDL 2.0.1 Linux Make编译错误