增加单例的饿汉模式支持,饿汉单例模式本身是多线程安全的

master
ichdream 2021-09-10 15:55:18 +08:00
parent 19ca5f026c
commit e0c7e3db25
2 changed files with 45 additions and 10 deletions

View File

@ -6,28 +6,45 @@
#include <mutex> #include <mutex>
using namespace std; using namespace std;
class Singleton class Singleton_Lazy
{ {
public: public:
static Singleton* getInstance(){ static Singleton_Lazy* getInstance(){
printf("This is Singleton Lazy mode...\n");
if (instance == NULL){ if (instance == NULL){
m_mutex.lock(); m_mutex.lock();
if (instance == NULL){ if (instance == NULL){
printf("创建新的实例\n"); printf("创建新的实例\n");
instance = new Singleton(); instance = new Singleton_Lazy();
} }
m_mutex.unlock(); m_mutex.unlock();
} }
return instance; return instance;
} }
private: private:
Singleton(){} Singleton_Lazy(){}
static Singleton* instance; static Singleton_Lazy* instance;
static std::mutex m_mutex; static std::mutex m_mutex;
}; };
Singleton* Singleton::instance = NULL; Singleton_Lazy* Singleton_Lazy::instance = NULL;
std::mutex Singleton::m_mutex; std::mutex Singleton_Lazy::m_mutex;
class Singleton_Hungry
{
public:
static Singleton_Hungry* getInstance()
{
printf("This Singleton Hungry mode...\n");
return instance;
}
private:
Singleton_Hungry() {}
static Singleton_Hungry* instance;
};
Singleton_Hungry* Singleton_Hungry::instance = new Singleton_Hungry;
#endif //__SINGLETON_H__ #endif //__SINGLETON_H__

View File

@ -53,9 +53,18 @@ int main()
#else #else
#define THREAD_NUM 5 #define THREAD_NUM 5
#include<pthread.h> #include<pthread.h>
void* callSingleton(void *pPM) void* callSingleton_Lazy(void *pPM)
{ {
Singleton *s = Singleton::getInstance(); Singleton_Lazy *s = Singleton_Lazy::getInstance();
pthread_t nThreadNum = pthread_self();
// sleep(50);
printf("线程编号为%ld\n", nThreadNum);
return 0;
}
void* callSingleton_Hungry(void *pPM)
{
Singleton_Hungry *s = Singleton_Hungry::getInstance();
pthread_t nThreadNum = pthread_self(); pthread_t nThreadNum = pthread_self();
// sleep(50); // sleep(50);
printf("线程编号为%ld\n", nThreadNum); printf("线程编号为%ld\n", nThreadNum);
@ -66,11 +75,20 @@ int main()
{ {
pthread_t threads_pool[THREAD_NUM]; pthread_t threads_pool[THREAD_NUM];
int tids[THREAD_NUM]; int tids[THREAD_NUM];
printf("Singleton Lazy mode:\n");
for(int i = 0; i < THREAD_NUM; i++) for(int i = 0; i < THREAD_NUM; i++)
{ {
tids[i] = pthread_create(&threads_pool[i], NULL, callSingleton, NULL); tids[i] = pthread_create(&threads_pool[i], NULL, callSingleton_Lazy, NULL);
pthread_join(threads_pool[i], (void**)&tids[i]); pthread_join(threads_pool[i], (void**)&tids[i]);
} }
printf("Singleton Hungry mode:\n");
for(int i = 0; i < THREAD_NUM; i++)
{
tids[i] = pthread_create(&threads_pool[i], NULL, callSingleton_Hungry, NULL);
pthread_join(threads_pool[i], (void**)&tids[i]);
}
return 0; return 0;
} }