如何在不使用C ++ 11的情况下实现多线程安全单例

问题描述 投票:67回答:6

既然C ++ 11有多线程,我想知道在不使用互斥锁的情况下实现延迟初始化单例的正确方法是什么(出于性能原因)。我想出了这个,但是我并不擅长编写无锁代码,所以我正在寻找更好的解决方案。

// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
# include <atomic>
# include <thread>
# include <string>
# include <iostream>
using namespace std;
class Singleton
{

public:
    Singleton()
    {
    }
static  bool isInitialized()
    {
        return (flag==2);
    }
static  bool initizalize(const string& name_)
    {
        if (flag==2)
            return false;// already initialized
        if (flag==1)
            return false;//somebody else is initializing
        if (flag==0)
        {
            int exp=0;
            int desr=1;
            //bool atomic_compare_exchange_strong(std::atomic<T>* obj, T* exp, T desr)
            bool willInitialize=std::atomic_compare_exchange_strong(&flag, &exp, desr);
            if (! willInitialize)
            {
                //some other thread CASed before us
                std::cout<<"somebody else CASed at aprox same time"<< endl;
                return false;
            }
            else 
            {
                initialize_impl(name_);
                assert(flag==1);
                flag=2;
                return true;
            }
        }
    }
static void clear()
{
    name.clear();
    flag=0;
}
private:
static  void initialize_impl(const string& name_)
{
        name=name_;
}
static  atomic<int> flag;
static  string name;
};
atomic<int> Singleton::flag=0;
string Singleton::name;
void myThreadFunction()
{
    Singleton s;
    bool initializedByMe =s.initizalize("1701");
    if (initializedByMe)
        s.clear();

}
int main()
{
    while (true)
    {
        std::thread t1(myThreadFunction);
        std::thread t2(myThreadFunction);
        t1.join();
        t2.join();
    }
    return 0;
}

请注意,clear()仅用于测试,真正的单例不具备该功能。

c++ multithreading c++11 singleton atomic
6个回答
139
投票

C ++ 11不再需要手动锁定。如果已经初始化静态局部变量,则并发执行应该等待。

§6.7 [stmt.dcl] p4

如果控制在初始化变量时同时进入声明,则并发执行应等待初始化完成。

因此,简单有一个像这样的static函数:

static Singleton& get() {
  static Singleton instance;
  return instance;
}

这将在C ++ 11中正常工作(当然,只要编译器正确实现了标准的那部分)。


当然,真正正确的答案是to not use a singleton, period


36
投票

对我来说,使用C ++ 11实现单例的最佳方法是:

class Singleton {
 public:
  static Singleton& Instance() {
    // Since it's a static variable, if the class has already been created,
    // it won't be created again.
    // And it **is** thread-safe in C++11.
    static Singleton myInstance;

    // Return a reference to our instance.
    return myInstance;
  }

  // delete copy and move constructors and assign operators
  Singleton(Singleton const&) = delete;             // Copy construct
  Singleton(Singleton&&) = delete;                  // Move construct
  Singleton& operator=(Singleton const&) = delete;  // Copy assign
  Singleton& operator=(Singleton &&) = delete;      // Move assign

  // Any other public methods.

 protected:
  Singleton() {
    // Constructor code goes here.
  }

  ~Singleton() {
    // Destructor code goes here.
  }

 // And any other protected methods.
}

3
投票

恕我直言,实现单例的最佳方法是使用“双重检查,单锁”模式,您可以在C ++ 11中实现这种模式:Double-Checked Locking Is Fixed In C++11这种模式在已经创建的情况下很快,只需要一个指针比较,在第一用例中是安全的。

正如之前的回答中所提到的,C ++ 11保证了静态局部变量Is local static variable initialization thread-safe in C++11?的构造顺序安全性,因此您可以安全地使用该模式。但是,Visual Studio 2013还不支持它:-( See the "magic statics" row on this page,所以如果你使用VS2013,你仍然需要自己动手。

不幸的是,没有什么是简单的。上面模式引用的sample code无法从CRT初始化调用,因为静态std :: mutex有一个构造函数,因此不能保证在第一次调用getton之前初始化,如果所谓的调用是副作用的话CRT初始化。为了解决这个问题,你必须使用而不是互斥锁,而是使用指向互斥锁的指针,它保证在CRT初始化开始之前进行零初始化。然后你必须使用std :: atomic :: compare_exchange_strong来创建和使用互斥锁。

我假设即使在CRT初始化期间调用,C ++ 11线程安全的本地静态初始化语义也能正常工作。

因此,如果您有可用的C ++ 11线程安全的本地静态初始化语义,请使用它们。如果没有,你还有一些工作要做,甚至更多,如果你希望你的单例在CRT初始化期间是线程安全的。


2
投票

由于您没有按预期使用代码,因此难以阅读您的方法...也就是说,单例的常见模式是调用instance()来获取单个实例,然后使用它(如果您真的需要单例,没有构造函数应该公开)。

无论如何,我不认为你的方法是安全的,考虑到两个线程试图获取单例,第一个获得更新标志的将是唯一一个初始化,但initialize函数将提前退出第二个,并且该线程可能会在第一个线程完成初始化之前继续使用单例。

你的initialize的语义被打破了。如果您尝试描述/记录函数的行为,您将获得一些乐趣,并最终将描述实现而不是简单的操作。记录通常是一种简单的方法来仔细检查设计/算法:如果你最终描述的是如何而不是什么,那么你应该回到设计。特别是,无法保证在initialize完成后对象实际上已被初始化(仅当返回值为true时,有时如果它是false,但并非总是如此)。


1
投票
#pragma once

#include <memory>
#include <mutex>

namespace utils
{

template<typename T>
class Singleton
{
private:
    Singleton<T>(const Singleton<T>&) = delete;
    Singleton<T>& operator = (const Singleton<T>&) = delete;

    Singleton<T>() = default;

    static std::unique_ptr<T> m_instance;
    static std::once_flag m_once;

public:
    virtual ~Singleton<T>() = default;

    static T* getInstance()
    {
        std::call_once(m_once, []() {
            m_instance.reset(new T);
        });
        return m_instance.get();
    }

    template<typename... Args>
    static T* getInstance2nd(Args&& ...args)
    {
        std::call_once(m_once, [&]() {
            m_instance.reset(new T(std::forward<Args>(args)...));
        });
        return m_instance.get();
    }
};

template<typename T> std::unique_ptr<T> Singleton<T>::m_instance;
template<typename T> std::once_flag Singleton<T>::m_once;

}

此版本符合并发免费,其中c ++ 11标准不能保证100%支持。它还提供了一种实例化“拥有”实例的灵活方式。即使c ++ 11及更高版本中的魔术静态单词足够,开发人员也可能需要对实例创建进行更多控制。


1
投票
template<class T> 
class Resource
{
    Resource<T>(const Resource<T>&) = delete;
    Resource<T>& operator=(const Resource<T>&) = delete;
    static unique_ptr<Resource<T>> m_ins;
    static once_flag m_once;
    Resource<T>() = default;

public : 
    virtual ~Resource<T>() = default;
    static Resource<T>& getInstance() {
        std::call_once(m_once, []() {
            m_ins.reset(new Resource<T>);
        });
        return *m_ins.get();
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.