首页 > 编程语言 > 详细

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

时间:2020-05-10 23:56:40      阅读:122      评论:0      收藏:0      [点我收藏+]

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

#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)

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!