zoukankan      html  css  js  c++  java
  • C++线程安全的单例模式

    单例模式,是设计模式的一种,是指一个类只有一个实例。
    首先看实现的代码

    1. singleton.h
    #ifndef SINGLETON_H
    #define SINGLETON_H
    #include <stdio.h>
    #include <pthread.h>
    #include <malloc.h>
    
    class Singleton {
      public:
        static Singleton *GetInstance();
    
      private:
         Singleton() {
    	printf("create singleton\n");
        };
        Singleton(const Singleton &) {
        };				//禁止拷贝
        Singleton & operator=(const Singleton &) {
        };				//禁止赋值
      private:
        static Singleton *s;
    
    };
    
    extern pthread_mutex_t mutex;
    #endif
    
    
    1. singleton.cpp
    include "singleton.h"
    Singleton *Singleton::s = NULL;
    
    Singleton *Singleton::GetInstance()
    {
        if (s == NULL) {
    	pthread_mutex_lock(&mutex);
    	if (s == NULL) {
    	    s = new Singleton();
    	}
    	pthread_mutex_unlock(&mutex);
        }
        return s;
    }
    
    
    1. main.cpp
    #include<stdio.h>
    #include<pthread.h>
    #include "singleton.h"
    pthread_mutex_t mutex;
    
    int main()
    {
    
        pthread_mutex_init(&mutex, NULL);
        Singleton *s = Singleton::GetInstance();
        Singleton *s1 = Singleton::GetInstance();
        pthread_mutex_destroy(&mutex);
    }
    
    1. 需要将类的构造函数,赋值构造函数,拷贝构造函数设为私有,另外,
      当 if (s == NULL)这一行实际是一行优化代码,这一行目的是,每次get实例
      时候,不需要去加锁,只有它为空的时候,才去加锁。

    作者: 盛夏落木

    出处: https://www.cnblogs.com/wanshuafe/

    关于作者:专注云存储,文件系统领域,请多多赐教!

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接 如有问题, 可邮件(wanshuafe@163.com)咨询.

  • 相关阅读:
    洛谷P1306 斐波那契公约数
    Codevs 1688 求逆序对(权值线段树)
    poj1006 Biorhythms
    2017-9-2 NOIP模拟赛
    洛谷P1633 二进制
    洛谷P2513 [HAOI2009]逆序对数列
    洛谷P2687 [USACO4.3]逢低吸纳Buy Low, Buy Lower
    洛谷P2285 [HNOI2004]打鼹鼠
    2017-8-31 NOIP模拟赛
    洛谷P2134 百日旅行
  • 原文地址:https://www.cnblogs.com/wanshuafe/p/11570171.html
Copyright © 2011-2022 走看看