使用std::call_once时遇到异常抛出Bug

13
我尝试运行文档页面https://en.cppreference.com/w/cpp/thread/call_once中的示例,但它无法按预期工作。它会无限卡住。我想知道为什么会出现这种情况,或者它是否只是与某些特定编译器版本相关的错误。这是我用来运行程序的https://repl.it/repls/UtterJubilantArchitects
#include <iostream>
#include <thread>
#include <mutex>

std::once_flag flag1, flag2;

void simple_do_once()
{
    std::call_once(flag1, [](){ std::cout << "Simple example: called once\n"; });
}

void may_throw_function(bool do_throw)
{
  if (do_throw) {
    std::cout << "throw: call_once will retry\n"; // this may appear more than once
    throw std::exception();
  }
  std::cout << "Didn't throw, call_once will not attempt again\n"; // guaranteed once
}

void do_once(bool do_throw)
{
  try {
    std::call_once(flag2, may_throw_function, do_throw);
  }
  catch (...) {
  }
}

int main()
{
    std::thread st1(simple_do_once);
    std::thread st2(simple_do_once);
    std::thread st3(simple_do_once);
    std::thread st4(simple_do_once);
    st1.join();
    st2.join();
    st3.join();
    st4.join();

    std::thread t1(do_once, true);
    std::thread t2(do_once, true);
    std::thread t3(do_once, false);
    std::thread t4(do_once, true);
    t1.join();
    t2.join();
    t3.join();
    t4.join();
}

3
问题与libstdc++有关(请注意,repl.it使用带有libstdc ++的clang,可以通过检查__GLIBCXX__宏进行验证)。 它在libc ++中不存在,例如https://wandbox.org/permlink/7rPCL57q8E55Eq6m。 请参见下面的答案以及我的评论。 - walnut
谢谢,这对我来说是个解决方案) - Despise
1个回答

6
这种行为是实现错误。call_once(通过pthread_once)据说使用int pthread_mutex_lock(pthread_mutex_t *)和int pthread_mutex_unlock(pthread_mutex_t *),以及两者之间的代码,但它们并不支持异常安全。
一些相关错误链接:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66146, sourceware.org/bugzilla/show_bug.cgi?id=18435, austingroupbugs.net/view.php?id=863#c2619
实现细节:
这是来自gnu.org的pthread实现。
int
__pthread_once (pthread_once_t *once_control, void (*init_routine) (void))
{
  __memory_barrier ();
  if (once_control->__run == 0)
    {
      __pthread_spin_lock (&once_control->__lock);

      if (once_control->__run == 0)
      {
        init_routine ();
        __memory_barrier ();
        once_control->__run = 1;
      }

      __pthread_spin_unlock (&once_control->__lock);
    }

  return 0;
}

这是来自 g++ 7.4.0 软件包(Ubuntu 18.4.0)的 call_once 实现: (我们有活跃的 _GLIBCXX_HAVE_TLS 分支)
  /// call_once
  template<typename _Callable, typename... _Args>
    void
    call_once(once_flag& __once, _Callable&& __f, _Args&&... __args)
    {
      // _GLIBCXX_RESOLVE_LIB_DEFECTS
      // 2442. call_once() shouldn't DECAY_COPY()
      auto __callable = [&] {
      std::__invoke(std::forward<_Callable>(__f),
            std::forward<_Args>(__args)...);
      };
#ifdef _GLIBCXX_HAVE_TLS
      __once_callable = std::__addressof(__callable);
      __once_call = []{ (*(decltype(__callable)*)__once_callable)(); };
#else
      unique_lock<mutex> __functor_lock(__get_once_mutex());
      __once_functor = __callable;
      __set_once_functor_lock_ptr(&__functor_lock);
#endif

      int __e = __gthread_once(&__once._M_once, &__once_proxy);

#ifndef _GLIBCXX_HAVE_TLS
      if (__functor_lock)
        __set_once_functor_lock_ptr(0);
#endif

#ifdef __clang_analyzer__
      // PR libstdc++/82481
      __once_callable = nullptr;
      __once_call = nullptr;
#endif

      if (__e)
          __throw_system_error(__e);
    }

__once_proxy 是:

extern "C"
  {
    void __once_proxy()
    {
#ifndef _GLIBCXX_HAVE_TLS
      function<void()> __once_call = std::move(__once_functor);
      if (unique_lock<mutex>* __lock = __get_once_functor_lock_ptr())
      {
        // caller is using new ABI and provided lock ptr
        __get_once_functor_lock_ptr() = 0;
        __lock->unlock();
      }
      else
        __get_once_functor_lock().unlock();  // global lock
#endif
      __once_call();
    }
  }

_GLIBCXX_END_NAMESPACE_VERSION
} // namespace std

这是 pthread_once 的实现:

struct __pthread_once
{
  int __run;
  __pthread_spinlock_t __lock;
};

以及__pthread_spinlock_t:

typedef __volatile int __pthread_spinlock_t;

__pthread_spin_lock是一个类型定义,用于

void
__spin_lock_solid (spin_lock_t *lock)
{
  while (__spin_lock_locked (lock) || ! __spin_try_lock (lock))
    /* Yield to another thread (system call).  */
    __swtch_pri (0);
}

就我个人而言,当互斥解锁保护是针对异常的情况时,我并不认为这些领域有什么问题。我们采用双重检查锁和调用可调用对象的方式。

我认为,可以使用具有noexcept特性的可调用对象或使用lock_guard/unique_lock的双重检查锁(如果您确定读取变量的操作是原子的),作为解决方案。我遵循了 walnut 的解决方案,安装了 libc++-dev、libc++abi-dev,并使用以下代码进行编译:

clang++ -stdlib=libc++ -lc++abi 

并且它运行良好。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接