singleton.h,下面是源码
#include <unistd.h> #include <pthread.h> using namespace std; class Lock { private: pthread_mutex_t m_lock; public: Lock(pthread_mutex_t cs) : m_lock(cs) { pthread_mutex_lock(&m_lock); } ~Lock() { pthread_mutex_unlock(&m_lock); } };//锁类,实现多线程环境下高效工作 class Singleton { private: Singleton() {}; Singleton(const Singleton &); Singleton& operator = (const Singleton &); public: static Singleton *Instantialize(); static Singleton *pInstance; static pthread_mutex_t mutex; }; #endif
singleton.cc文件
<pre name="code" class="html">#include "singleton.h" pthread_mutex_t Singleton::mutex = PTHREAD_MUTEX_INITIALIZER; Singleton* Singleton::pInstance = 0; Singleton* Singleton::Instantialize() { if(pInstance == NULL) { //double check Lock lock(mutex); //用lock实现线程安全,用资源管理类,实现异常安全 //使用资源管理类,在抛出异常的时候,资源管理类对象会被析构,析构总是发生的无论是因为异常抛出还是语句块结束。 if(pInstance == NULL) { pInstance = new Singleton(); } } return pInstance; } ~
<pre name="code" class="html">#include <iostream> #include <cassert> #include <unistd.h> #include <pthread.h> #include "singleton.h" int main(int argc, char *argv[]) { Singleton *p = Singleton::Instantialize(); Singleton *q = Singleton::Instantialize(); assert(p != q); return 0; }
<pre name="code" class="html">#lizhiming CC=gcc CXX=g++ AR=ar ARFLAGS=cru CURRENT_DIR=$(shell echo `pwd`) PARENT_DIRNAME=$(shell basename $(shell dirname $(CURRENT_DIR))) SOURCE_DIR=$(CURRENT_DIR)/src PREFIX=${CURRENT_DIR} DEBUG := CFLAGS := $(DEBUG) -g -c -fPIC -Wshadow -Wcast-qual -Wcast-align -Wwrite-strings -Wsign-compare -Winvalid-pch -fms-extensions -Wall -I./include CPPFLAGS=$(CFLAGS) -Woverloaded-virtual -Wsign-promo -fno-gnu-keywords LDFLAGS=-L/usr/local/lib -lpthread DIRNAME=$(shell basename `pwd`) SRCXXS := $(wildcard *.cc) $(wildcard ./src/*.cc) SRCS := $(SRCXXS) CXXOBJS := $(patsubst %.cc, %.o, $(SRCXXS)) OBJS := ${CXXOBJS} DEPS := $(patsubst %.o, %.d, $(OBJS)) TARGET := lib$(PARENT_DIRNAME)_$(DIRNAME).so ARFLAGS := -cvq TARGET_A_LIB := lib$(PARENT_DIRNAME)_$(DIRNAME).a all : $(TARGET) $(TARGET_A_LIB) $(TARGET_A_LIB): $(OBJS) @ar $(ARFLAGS) $@ $^ @ranlib $@ $(TARGET) : $(OBJS) $(CXX) $(OBJS) $(LDFLAGS) -o $@ -shared -include $(DEPS) %.o : %.cc $(CXX) $(CPPFLAGS) $< -o $@ t: @echo "DIRNAME:" $(DIRNAME) @echo "PARENT_DIRNAME:" $(PARENT_DIRNAME) @echo "SRCS:" $(SRCS) @echo "OBJS:" $(OBJS) @echo "CFLAGS:" $(CFLAGS) @echo "CPPFLAGS:" $(CPPFLAGS) @echo "ARFLAGS:" $(ARFLAGS) clean: rm -rf *.o *.d *.a $(OBJS) $(DEPS) $(TARGET)
原文地址:http://blog.csdn.net/nanfenglei23/article/details/42458613