linux环境下多线程中单例模式:利用pthread_once的特性
首先介绍一下pthread_once
int pthread_once(pthread_once_t *once_control, void (*init_routine) (void));
功能:本函数使用初值为PTHREAD_ONCE_INIT的once_control变量,保证init_routine()函数在本进程执行序列中仅执行一次。
#ifndef __SINGLETON__
#define __SINGLETON__
#include<pthread.h>
template<typename T>
class Singleton{
private:
static pthread_once_t ponce;
static T* value;
public:
static T& instance(){
pthread_once(&ponce,&Singleton::init);
}
static void init(){
// cout<<"exec init"<<endl;
value=new T();
}
};
template<typename T>
pthread_once_t Singleton<T>::ponce=PTHREAD_ONCE_INIT;
template<typename T>
T *Singleton<T>::value=NULL;
#endif
测试函数如下
#include<iostream>
#include<thread>
#include<vector>
#include&