当前位置:网站首页>Thread safe sigleton (singleton mode)
Thread safe sigleton (singleton mode)
2022-04-23 20:59:00 【Descosmos】
The singleton pattern
The definition of singleton pattern and its most basic implementation will not be mentioned more , It's important to point out that , For general singleton mode , On the basis of if(hold_ == NULL) It is obviously difficult to meet the requirements of thread safety , Therefore, this article through pthread_once To achieve .
Be careful , You can also use thread synchronization mechanism , Like locks , Semaphore, etc .
template<typename T>
class Signleton: boost noncopyable{
public:
static T& instance(){
pthead_once(&ponce_, &Signleton::init);
return *value_;
}
private:
// Set constructors and destructors to private, So that singleton mode cannot be created on the stack
Signleton();
~Signleton();
static void init(){
value_ = new T();
}
private:
static pthread_once_t ponce_;
static T* value_; // Data in singleton mode
};
// Must be defined in the header file static Variable
pthread_once_t Signleton<T>::ponce_ = PTHREAD_ONCE_INIT;
template<typename T>
T* Signleton<T>::value_ NULL;
Usage method
Foo &foo = Sigleton<Foo>::instance();
Be careful
This singleton pattern does not consider how to destroy objects .
版权声明
本文为[Descosmos]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/111/202204210545298121.html
边栏推荐
- 启牛学堂有用吗,推荐的证券账户是否安全
- ROS学习笔记-----ROS的使用教程
- Matlab matrix index problem
- CONDA environment management command
- Introduction to intrusion detection data set
- Singleton mode
- Google tries to use rust in Chrome
- 小米手机全球已舍弃“MI”品牌,全面改用“xiaomi”全称品牌
- Minecraft 1.12.2 module development (43) custom shield
- Selenium 显示等待WebDriverWait
猜你喜欢
Reentrant function
Problem brushing plan -- dynamic programming (III)
Question brushing plan - depth first search DFS (I)
opencv应用——以图拼图
中创存储|想要一个好用的分布式存储云盘,到底该怎么选
On the three paradigms of database design
3-5 obtaining cookies through XSS and the use of XSS background management system
Rust更适合经验较少的程序员?
Recommended usage scenarios and production tools for common 60 types of charts
Amazon and epic will be settled, and the Microsoft application mall will be opened to third parties
随机推荐
软件测试要怎么学?自学还是培训看完这篇文章你就懂了
Learn to C language fourth day
常用60类图表使用场景、制作工具推荐
MySQL stored procedures and functions
Addition, deletion, modification and query of MySQL advanced table
Selenium displays webdriverwait
Problem brushing plan -- dynamic programming (III)
2.整理华子面经--2
Go limit depth traversal of files in directory
IOT 设计与开发
Cmake project under vs2019: calculating binocular parallax using elas method
Queue template code
3-5通过XSS获取cookie以及XSS后台管理系统的使用
深入探究ASP.NET Core读取Request.Body的正确方式
Is rust more suitable for less experienced programmers?
Factory mode
go reflect
Tensorflow realizes gradient accumulation, and then returns
IOT design and development
一些接地气的话儿