码迷,mamicode.com
首页 > 编程语言 > 详细

C++-饿汉式声明(单例声明)和懒汉式声明(单例声明 线程thread)

时间:2020-05-11 01:18:29      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:static   thread   stat   initial   class   开始   null   std   let   

饿汉式声明, 一开始的时候对单例进行声明

#include <iostream>

using namespace std; 

class Singleton{ 
public:
    static Singleton& getInstance(void){
        return s_instance;
    }
    void print(void) {
        cout<<m_data<<endl;
    }

private:
    Singleton(int data = 0):m_data(data){
        cout << "单例被创建" << endl;     
    }; 
    Singleton(const Singleton&); 
    int m_data; 
    static Singleton s_instance; 
}; 

Singleton Singleton::s_instance = 123; 

int main(void){
    Singleton& s1 = Singleton::getInstance(); 
    Singleton& s2 = Singleton::getInstance(); 
    Singleton& s3 = Singleton::getInstance(); 
    
    cout << &s1 << endl; 
    cout << &s2 << endl; 
    cout << &s3 << endl; 
    return 0; 
}

懒汉式声明, 在进行调用的时候进行声明,这里使用了线程里的互斥锁

#include <iostream>

using namespace std; 


class Singleton{
public:
    static Singleton& getInstance(void){
        pthread_mutex_lock(&mutex);
        if(s_instance == NULL){
            s_instance = new Singleton(123);          
        }
        ++s_count; 
        pthread_mutex_unlock(&mutex); 
        return *s_instance;
    }
    //所有的使用者都不用再销毁 
    void release(void) {
        pthread_mutex_lock(&mutex); 
        if (--s_count == 0){
            delete s_instance;
            s_instance = NULL; 
        }  
        pthread_mutex_unlock(&mutex); 
    }
    //单列对象不用销毁 
    void print(void) {
        cout << m_data << endl; 
    }
private:
    Singleton(int data=0):m_data(data){
        cout << "创建单例" << endl; 
    } 
    Singleton(const Singleton&); 
    ~Singleton(void){
        cout << "单例被删除" << endl; 
    }
    int m_data; 
    static Singleton* s_instance; 
    static int s_count; 
    static pthread_mutex_t mutex;  
};     

Singleton* Singleton::s_instance = NULL;//进行私有化的生成操作 
int Singleton::s_count = 0;
//互斥锁定义和初始化  
pthread_mutex_t Singleton::mutex = PTHREAD_MUTEX_INITIALIZER; 

int main() {
    Singleton& s1 = Singleton::getInstance(); 
    Singleton& s2 = Singleton::getInstance(); 
    Singleton& s3 = Singleton::getInstance(); 
    
    cout << "&s1" << &s1 << endl; 
    cout << "&s2" << &s2 << endl; 
    cout << "&s3" << &s3 << endl; 
    
    s1.print(); 
    s1.release(); 
    
    s2.print(); 
    s2.release(); 
    
    s3.print(); 
    s3.release(); 

}

 

C++-饿汉式声明(单例声明)和懒汉式声明(单例声明 线程thread)

标签:static   thread   stat   initial   class   开始   null   std   let   

原文地址:https://www.cnblogs.com/hyq-lst/p/12866269.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!