thread safe lazy initialization singleton
来源:互联网 发布:手机视频文件加密软件 编辑:程序博客网 时间:2024/06/06 12:47
double-check来保证thread safety,此法可能由于乱序执行而失效
参考:http://www.javaworld.com/article/2075306/java-concurrency/can-double-checked-locking-be-fixed-.html
1 class Singleton 2 { 3 private: 4 static Singleton* m_instance;
static locker llock; 5 Singleton(){} 6 public: 7 static Singleton* getInstance();
8 }; 9 10 Singleton* Singleton::getInstance()11 {12 if(NULL == m_instance) //如果没有这句,当已经实例化后,每次通过getInstance()获取时都要先试图加锁,非常耗时13 {14 llock.lock();15 if(NULL == m_instance) //在初始化时只能有一个线程实例化对象,其它线程即便随后获得了锁资源,也不会再次实例化16 {17 m_instance = new Singleton;18 }llock.unlock();20 }
21 return m_instance;
22 }
Singleton* Singleton::m_instance = 0;
可以采用pthread_once实现真正的thread safe lazy initialization singleton:
在多线程环境中,有些事仅需要执行一次。通常当初始化应用程序时,可以比较容易地将其放在main函数中。但当你写一个库时,就不能在main里面初始化了,你可以用静态初始化,但使用一次初始化(pthread_once)会比较容易些。
int pthread_once(pthread_once_t *once_control, void (*init_routine) (void));
功能:本函数使用初值为PTHREAD_ONCE_INIT的once_control变量保证init_routine()函数在本进程执行序列中仅执行一次。
在多线程编程环境下,尽管pthread_once()调用会出现在多个线程中,init_routine()函数仅执行一次,究竟在哪个线程中执行是不定的,是由内核调度来决定。
Linux Threads使用互斥锁和条件变量保证由pthread_once()指定的函数执行且仅执行一次,而once_control表示是否执行过。
如果once_control的初值不是PTHREAD_ONCE_INIT(Linux Threads定义为0),pthread_once() 的行为就会不正常。
在LinuxThreads中,实际"一次性函数"的执行状态有三种:NEVER(0)、IN_PROGRESS(1)、DONE (2),如果once初值设为1,则由于所有pthread_once()都必须等待其中一个激发"已执行一次"信号,因此所有pthread_once ()都会陷入永久的等待中;如果设为2,则表示该函数已执行过一次,从而所有pthread_once()都会立即返回0。
template<typename T>class Singleton : boost:noncopyable{ public:static T& instance(){pthread_once(&ponce,&Singleton:init);}private:Singleton();~Singleton();static void init(){ value_ = new T();}private:static pthread_once_t ponce;static T* value_;};template<typename T>pthread_once_t Singleton<T>::ponce = PTHREAD_ONCE_INIT;template<typename T>T* Singleton<T>::value_ = NULL;//使用方法Foo& foo = Singleton<Foo>::instance();
- thread safe lazy initialization singleton
- [LinkedIn] singleton, thread safe
- muduo : Thread-safe Singleton
- Thread safe Singleton in C#
- How to write a thread-safe Singleton?
- Design Patterns I - Singleton, Double-Checked locking, Lazy Initialization
- Lazy initialization
- Lazy Initialization
- Thread-Safe Singleton is Well Supported in C++11
- Thread-safe, Signal-safe
- thread safe
- PHP Thread Safe and Non Thread Safe
- Lazy initialization holder class模式
- Lazy initialization的一个问题
- Lazy initialization holder class模式
- 惰性初始模式 Lazy Initialization
- Lazy initialization holder class模式
- Thread Safe In Servlet
- openldap 使用mysql作为后端数据库
- zoj题目分类详细的
- Linux pptp client 指定协议连接VPN(pap)
- ContextClassLoader
- 8月2日----TCP Socket 编程
- thread safe lazy initialization singleton
- 啊哈,算法! -----dfs1
- 2100 Seeding【dfs】
- 手势识别器(UIImageView)
- !HDU 4346 插旗子RGR的插法有多少种-思维&正难则逆&思维!
- Ubuntu下nginx的编译与安装
- 计算机网络面试题
- JSP中页面跳转response.sendRedirect()和request.getRequestDispatcher()的区别
- Codeforces 4B