std :: call_once引发std :: system_error(未知错误-1) [英] std::call_once throws std::system_error (Unknown error -1)

查看:514
本文介绍了std :: call_once引发std :: system_error(未知错误-1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was using the C++ OpenCL wrapper and I was wondering why my program crashed. I discovered any call to std::call_once was throwing an error.

#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,然后将引发异常.

As said in the comments by Praetorian, std::call_once need to call the system threading library. More specifically, it will call __gthread_once. If the executable is not linked to pthread, that function will return -1 and will then cause the exception to be thrown.

要使程序成为启用了pthread的-pthread选项,必须将其同时传递给编译器和链接器,如不够不仅仅是因为其他宏.对于CMake用户,有一个现成的模块,可以帮助添加对pthread(或任何系统线程库)的支持,可以这样使用:

To make a program pthread-enabled -pthread option needs to be passed both to compiler and linker, as stated in gcc documentation. Just linking with -lpthread sometimes is not enough and not just because of additional macros. For CMake users there is an out of the box module that can help adding support for pthread (or any system threading library) that can be used like that:

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

这将在必要时添加所有必需的编译和链接标志.

This will add any required compile and link flags if necessary.

这篇关于std :: call_once引发std :: system_error(未知错误-1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆