请问你用过哪些设计模式,介绍一下单例模式的多线程安全问题
//懒汉模式 class Singleton { private: Singleton(){} private: static Singleton* instance; public: static Singleton* getInstance(); }; Singleton* Singleton::instance = NULL; Singleton* Singleton::getInstance() { if( instance == NULL ) { instance = new Singleton(); } return instance; } /*这样的代码在多线程场景存在一个问题,当某个线程调用getInstance并执行到new Singleton时恰好被挂起 此时另一个线程也调用getInstance发现instance仍然为空又会调用new Singleton于是就产生了多个Singleton实例,一个 解决方法就是加锁,如下: */ class Singleton { private: Singleton(){} private: static Singleton* instance; static pthread_mutex_t mutex; public: static Singleton* getInstance(); }; Singleton* Singleton::instance = NULL; pthread_mutex_t Singleton::mutex = PTHREAD_MUTEX_INITIALIZER; Singleton* Singleton::getInstance() { if( instance == NULL ) { pthread_mutex_lock( &mutex ); if( instance == NULL ) { instance = new Singleton(); } pthread_mutex_unlock( &mutex ); } return instance; } //饿汉模式 class Singleton { private: Singleton(){} private: static Singleton* instance; public: static Singleton* getInstance(); }; Singleton* Singleton::instance = new Singleton(); //这儿其实是定义静态变量,类中只是声明,不要觉得私有变量为什么在类外还能访问 Singleton* Singleton::getInstance() { return instance; }