使用std :: call_once引发错误的异常

时间:2019-05-10 19:39:20

标签: c++11

我尝试从文档页面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();
}

1 个答案:

答案 0 :(得分:6)

此行为是实现错误。 call_onse(通过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=66146sourceware.org/bugzilla/show_bug.cgi?id=18435austingroupbugs.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是

的typedef
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);
}

就个人而言,当互斥锁解锁保护不受例外影响时,我在这些区域看不到。我们在内部仔细检查了锁和Callable对象的调用。

我认为,除了Callable或带有lock_guard / unique_lock的复查锁(如果您确定读取变量的原子性)之外,不能将其用作解决方案。我一直关注walnut的解决方案, 安装了libc ++-dev,libc ++ abi-dev并使用

编译了此代码
clang++ -stdlib=libc++ -lc++abi 

效果很好。