【问题标题】:std::call_once() hangs on second call after callable threw on first callstd::call_once() 在第一次调用时可调用后挂起第二次调用
【发布时间】:2017-01-18 10:57:47
【问题描述】:

鉴于这段代码:

#include <mutex>
#include <iostream>

void f(bool doThrow) {
    if (doThrow) {
        std::cout << "Throwing" << std::endl;
        throw 42;
    }
    std::cout << "Not throwing" << std::endl;
}

std::once_flag flag;

void g(bool doThrow) {
    try {
        std::call_once(flag, f, doThrow);
        std::cout << "Returning" << std::endl;
    } catch (int i) {
        std::cout << "Caught " << i << std::endl;
    }
}

int main() {
    std::once_flag flag;
    g(true);
    g(true);
    g(false);
    g(true);
    g(false);
}

当使用g++ -std=c++11 -pthread -ggdb 编译时,我得到了输出:

Throwing
Caught 42

之后进程挂起:

#0  0x000003fff7277abf in futex_wait (private=0, expected=1, futex_word=0x2aaaacad144 <flag>) at ../sysdeps/unix/sysv/linux/futex-internal.h:61
#1  futex_wait_simple (private=0, expected=1, futex_word=0x2aaaacad144 <flag>) at ../sysdeps/nptl/futex-internal.h:135
#2  __pthread_once_slow (once_control=0x2aaaacad144 <flag>, init_routine=0x3fff7a8d870 <std::__once_proxy()>) at pthread_once.c:105
#3  0x000002aaaaaab06f in __gthread_once (__once=0x2aaaacad144 <flag>, __func=0x3fff7a8d870 <std::__once_proxy()>) at /usr/lib/gcc/x86_64-pc-linux-gnu/5.4.0/include/g++-v5/x86_64-pc-linux-gnu/bits/gthr-default.h:699
#4  0x000002aaaaaab6c8 in std::call_once<void (&)(bool), bool&> (__once=..., __f=@0x2aaaaaab08c: {void (bool)} 0x2aaaaaab08c <f(bool)>) at /usr/lib/gcc/x86_64-pc-linux-gnu/5.4.0/include/g++-v5/mutex:738
#5  0x000002aaaaaab192 in g (doThrow=true) at test.cpp:17
#6  0x000002aaaaaab287 in main () at test.cpp:27

但是当使用clang++ -std=c++11 -pthread -ggdb 编译时,我得到:

Throwing
Caught 42
Throwing
Caught 42
Not throwing
Returning
Returning
Returning

据我所知,这似乎是正确的行为。

这是一个 GCC 错误,只是我对 std::call_once 的语义感到困惑,还是我的代码不正确?

【问题讨论】:

  • gccg++ 不是同一个东西!
  • 复制了,好像是个bug。
  • @Meninx-メネンックス 那又怎样?一个是另一个的一部分。
  • @Meninx-メネンックス 这是关于 GCC(如GNU Compiler Collection),而不是gcc
  • @SamVarshavchik 我认为您在编译时缺少-pthread。请参阅 GCC PR 55394

标签: c++ c++11 g++ libstdc++ compiler-bug


【解决方案1】:

这看起来是 GNU C++ 库中的一个错误。


这肯定是一个错误,因为如果您尝试使用提供的在线编译器 (Coliru),即使默认的 std::call_once example from cppreference 也会挂起 :)

该错误发生在使用 pthreads 的 g++ linux 实现中。令我困惑的是this Wandbox example 运行良好。我检查了libstdc++的版本:

  • 魔杖盒:GLIBCXX: 20130411
  • 科利鲁:GLIBCXX: 20161221

因此我认为这是一个libstdc++ 错误,可能是this one,或更准确地说是this one

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 2020-04-13
    相关资源
    最近更新 更多