简体   繁体   English

c++ singleton 在使用互斥时是否需要 memory 屏障?

[英]Is c++ singleton need memory barrier while using mutex?

I have known that mutex can also bring the effect as memory barrier from here: Can mutex replace memory barriers , but I always see there is an memory barrier using in c++ singleton example as below, is the memory barrier unnecessary?我知道互斥锁也可以从这里带来 memory 屏障的效果: Can mutex replace memory barriers ,但我总是看到有一个 memory barrier using in c++ singleton barrier 如下所示,8839338802533 是不必要的吗?

Singleton* Singleton::getInstance() {
     Singleton* tmp = m_instance.load(std::memory_order_relaxed);
     std::atomic_thread_fence(std::memory_order_acquire);        
     if (tmp == nullptr) {
         std::lock_guard<std::mutex> lock(m_mutex);               // using mutex here
         tmp = m_instance.load(std::memory_order_relaxed);
         if (tmp == nullptr) {
             tmp = new Singleton;
             assert(tmp != nullptr);    
             std::atomic_thread_fence(std::memory_order_release); // using memory barrier here
             m_instance.store(tmp, std::memory_order_relaxed);
         }
     }
     return tmp;
 }

If you can use C++11, you do not need to program your own protection.如果可以使用C++11,就不需要自己编程保护了。

As also referenced here , all the needed stuff is already part of C++11. Copied from there:正如这里也提到的,所有需要的东西已经是 C++11 的一部分。从那里复制:

For the singleton pattern, double-checked locking is not needed:对于 singleton 模式,不需要双重检查锁定:

If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.如果控制在变量初始化时并发进入声明,则并发执行要等待初始化完成。 — § 6.7 [stmt.dcl] p4 — § 6.7 [stmt.dcl] p4

Singleton& GetInstance() {
  static Singleton s;
  return s;
}

The implementation will provide a memory barrier or whatever to protect your concurrent access.该实现将提供一个 memory 屏障或其他任何东西来保护您的并发访问。 So keep it simple as given in the example!因此,请保持示例中给出的简单!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM