如何在标准C ++中创建单例设计模式线程安全?当双重检查机制没有完全安全时? [英] How do I create singleton design pattern thread safe in standard C++? When double checking mechanism is not fully secured?

查看:63
本文介绍了如何在标准C ++中创建单例设计模式线程安全?当双重检查机制没有完全安全时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 98中是完全线程安全的,如果没有,我们如何在C ++ 98中实现线程安全的单例?



is it completely thread safe in C++ 98 if not, how we can achieve thread safe singleton in C++98 ?

MySingleton * GetInstance()
{
      if (m_pOnlyOneInstance == NULL)
      {
            EnterCriticalSection();
            if (m_pOnlyOneInstance == NULL)
            // Solution 1 and 2 gaps addressed by moving
            // critical section block and by re-doing this check!
            {
                  m_pOnlyOneInstance = new MySingleton();
            }
            LeaveCriticalSection();
      }
      return m_pOnlyOneInstance;
}





我的尝试:



在许多帖子中写道它不是完全线程安全的,在C ++ 11中,call_once()解决了单例thread_safe问题。如何在C ++ 98中完成?



What I have tried:

In many of post it is written that it is not completely thread safe,in C++11 call_once() has solved the singleton thread_safe problem.How to do it in C++98?

推荐答案

您好,



查看C ++和双重锁定的危险 [ ^ ]文章,找出为什么您的示例代码失败。



文章确实提供了线程安全单例样本。是的,它确实会遇到您尝试通过双重检查解决的性能问题。但它是线程安全的。至于性能,你需要知道在尝试为它找到解决方案之前调用GetInstance()方法的频率。
Hello,

Check the "C++ and the Perils of Double-Checked Locking"[^] article by Scott Meyers and Andrei Alexandrescu to find why the sample code you've got fails.

The article does provide a sample of thread-safe singleton. Yes, it does suffer from performance issue you are trying to solve with double checking. But it is thread safe. As for the performance, you need to have an idea of how often you are going to call the GetInstance() method before trying to find solution for it.


这篇关于如何在标准C ++中创建单例设计模式线程安全?当双重检查机制没有完全安全时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆