C++11 中线程安全局部静态变量初始化的成本?

Cost of thread-safe local static variable initialization in C++11?

我们知道局部静态变量初始化在C++11中是线程安全的,现代编译器完全支持这一点。 (Is local static variable initialization thread-safe in C++11?)

使其成为线程安全的成本是多少?我知道这很可能取决于编译器实现。

上下文:我有一个多线程应用程序(10 个线程)通过以下函数以非常高的速率访问单例对象池实例,我担心它的性能影响。

template <class T>
ObjectPool<T>* ObjectPool<T>::GetInst()
{
    static ObjectPool<T> instance;
    return &instance;
}

A look at the generated assembler code 有帮助。

来源

#include <vector>

std::vector<int> &get(){
  static std::vector<int> v;
  return v;
}
int main(){
  return get().size();
}

汇编程序

std::vector<int, std::allocator<int> >::~vector():
        movq    (%rdi), %rdi
        testq   %rdi, %rdi
        je      .L1
        jmp     operator delete(void*)
.L1:
        rep ret
get():
        movzbl  guard variable for get()::v(%rip), %eax
        testb   %al, %al
        je      .L15
        movl    get()::v, %eax
        ret
.L15:
        subq    , %rsp
        movl    guard variable for get()::v, %edi
        call    __cxa_guard_acquire
        testl   %eax, %eax
        je      .L6
        movl    guard variable for get()::v, %edi
        movq    [=11=], get()::v(%rip)
        movq    [=11=], get()::v+8(%rip)
        movq    [=11=], get()::v+16(%rip)
        call    __cxa_guard_release
        movl    $__dso_handle, %edx
        movl    get()::v, %esi
        movl    std::vector<int, std::allocator<int> >::~vector(), %edi
        call    __cxa_atexit
.L6:
        movl    get()::v, %eax
        addq    , %rsp
        ret
main:
        subq    , %rsp
        call    get()
        movq    8(%rax), %rdx
        subq    (%rax), %rdx
        addq    , %rsp
        movq    %rdx, %rax
        sarq    , %rax
        ret

相比

来源

#include <vector>

static std::vector<int> v;
std::vector<int> &get(){
  return v;
}
int main(){
  return get().size();
}

汇编程序

std::vector<int, std::allocator<int> >::~vector():
        movq    (%rdi), %rdi
        testq   %rdi, %rdi
        je      .L1
        jmp     operator delete(void*)
.L1:
        rep ret
get():
        movl    v, %eax
        ret
main:
        movq    v+8(%rip), %rax
        subq    v(%rip), %rax
        sarq    , %rax
        ret
        movl    $__dso_handle, %edx
        movl    v, %esi
        movl    std::vector<int, std::allocator<int> >::~vector(), %edi
        movq    [=13=], v(%rip)
        movq    [=13=], v+8(%rip)
        movq    [=13=], v+16(%rip)
        jmp     __cxa_atexit

我不太擅长汇编,但我可以看到在第一个版本中 v 有一个锁并且 get 没有内联,而在第二个版本中 get 基本上消失了。
您可以 play around 使用各种编译器和优化标志,但似乎没有编译器能够内联或优化锁,即使该程序显然是单线程的。
您可以将 static 添加到 get,这使得 gcc 内联 get 同时保留锁。

要了解这些锁和附加指令对您的编译器、标志、平台和周围代码的成本是多少,您需要进行适当的基准测试。
我希望锁有一些开销并且比内联代码慢得多,当你实际使用向量时它变得微不足道,但如果不测量你永远无法确定。

根据我的经验,这与常规互斥体(临界区)的成本完全一样。如果代码调用非常频繁,可以考虑使用普通的全局变量。

Jason Turner 在此处 https://www.youtube.com/watch?v=B3WWsKFePiM 进行了详尽的解释。

我放了一个示例代码来说明视频。由于thread-safety是主要问题,我尝试从多个线程调用该方法以查看其效果。

你可以认为编译器正在为你实现 double-checking 锁,即使他们可以做任何他们想做的事情来确保 thread-safety。但他们至少会添加一个分支来区分第一次初始化,除非优化器急切地在全局范围内进行初始化。

https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_C++11

#include <iostream>
#include <string>
#include <vector>
#include <thread>

struct Temp
{
  // Everytime this method is called, compiler has to check whether `name` is
  // constructed or not due to init-at-first-use idiom. This at least would 
  // involve an atomic load operation and maybe a lock acquisition.
  static const std::string& name() {
    static const std::string name = "name";
    return name;
  }

  // Following does not create contention. Profiler showed little bit of
  // performance improvement.
  const std::string& ref_name = name();
  const std::string& get_name_ref() const {
    return ref_name;
  }
};

int main(int, char**)
{
  Temp tmp;

  constexpr int num_worker = 8;
  std::vector<std::thread> threads;
  for (int i = 0; i < num_worker; ++i) {
    threads.emplace_back([&](){
      for (int i = 0; i < 10000000; ++i) {
        // name() is almost 5s slower
        printf("%zu\n", tmp.get_name_ref().size());
      }
    });
  }

  for (int i = 0; i < num_worker; ++i) {
    threads[i].join();
  }

  return 0;
}

在我的机器上,name() 版本比 get_name_ref() 慢 5s。

$ time ./test > /dev/null

我还使用编译器资源管理器查看 gcc 生成的内容。以下证明了双重检查锁模式:注意获取的原子负载和守卫。

name ()
{
  bool retval.0;
  bool retval.1;
  bool D.25443;
  struct allocator D.25437;
  const struct string & D.29013;
  static const struct string name;

  _1 = __atomic_load_1 (&_ZGVZL4namevE4name, 2);
  retval.0 = _1 == 0;
  if (retval.0 != 0) goto <D.29003>; else goto <D.29004>;
  <D.29003>:
  _2 = __cxa_guard_acquire (&_ZGVZL4namevE4name);
  retval.1 = _2 != 0;
  if (retval.1 != 0) goto <D.29006>; else goto <D.29007>;
  <D.29006>:
  D.25443 = 0;
  try
    {
      std::allocator<char>::allocator (&D.25437);
      try
        {
          try
            {
              std::__cxx11::basic_string<char>::basic_string (&name, "name", &D.25437);
              D.25443 = 1;
              __cxa_guard_release (&_ZGVZL4namevE4name);
              __cxa_atexit (__dt_comp , &name, &__dso_handle);
            }
          finally
            {
              std::allocator<char>::~allocator (&D.25437);
            }
        }
      finally
        {
          D.25437 = {CLOBBER};
        }
    }
  catch
    {
      if (D.25443 != 0) goto <D.29008>; else goto <D.29009>;
      <D.29008>:
      goto <D.29010>;
      <D.29009>:
      __cxa_guard_abort (&_ZGVZL4namevE4name);
      <D.29010>:
    }
  goto <D.29011>;
  <D.29007>:
  <D.29011>:
  goto <D.29012>;
  <D.29004>:
  <D.29012>:
  D.29013 = &name;
  return D.29013;
}