当前位置:网站首页>Thread safe singleton mode
Thread safe singleton mode
2022-07-03 02:15:00 【abs(ln(1+NaN))】
The so-called single example , Just some classes , There can only be one object
When an object is created , First, you need to open up space for this object , Then call the constructor to initialize this object . However, in singleton mode , This process can only occur once , In order to achieve this goal , We need to meet the following Two conditions :
(1) Let only one object exist in memory , This object needs Class , meanwhile Use static modification (static Decorated variables will be placed in the global area )
(2) To prevent other objects of this class from appearing outside the class , We're going to put various constructors Put it in private in ( If the default construction 、 There are parametric structures 、 Copy structure is not used , have access to delete Ban )
Catalog
One 、 Two cases of singleton mode
Two 、 Singleton mode of lazy way
1、 Create objects within classes ( Demand one )
2、 Constructor privatize or disable constructor ( Requirement 2 )
3、 Provide external interfaces for obtaining objects
3、 ... and 、 Singleton mode test
Four 、 expand : Starving model ( Brief introduction )
One 、 Two cases of singleton mode
On the basis of the above , Since it is creating objects , When should it be created ?? There are two situations , One is the way of hungry men , One is the lazy way .
- Starving Han style : Wash the bowl immediately , Convenient for cooking in the back . The object is created when the program starts running
- The lazy way : free from restraint , Don't cook until you need it . When objects are needed , Then take the initiative to create
Two 、 Singleton mode of lazy way
Let's take a singleton class as an example , This class uses the lazy way in singleton mode , That is, wait until you want to use objects before creating objects , Let's implement it in sequence according to the above two conditions .
1、 Create objects within classes ( Demand one )
The first is to create a unique object , And use static modification . The only object is inside the class , Outside the class, it is inevitable that you cannot obtain it in the following two ways
Sington sig; // error
Sington* sig = new Sington(); // error Use this object externally , It must be obtained directly or indirectly through classes , Since you want to get through classes , Then you need to add static To modify

static The decorated member function should be initialized outside the class , The initialization method is similar to that of class member functions outside the class
Variable type Class name :: Variable name = A variable's value 
2、 Constructor privatize or disable constructor ( Requirement 2 )
The above step just creates the only object we want , So how to prevent the outside world from creating objects ??
The answer is : Put the constructor in private in , Or disable some constructors
==》 When an object is created in a class , You can call private Constructor in ; But if the object is created outside the class ,public The corresponding constructor cannot be found in , At this point, an error will be reported

Why not : Suppose we use the only object we get sig To create other objects , In the memory Sington Class will have more than one object , This violates the principle of singleton , So we need to disable the copy constructor
Sington sig1(sig); // copy constructor 3、 Provide external interfaces for obtaining objects
Because the created object is placed in private Medium , Cannot access directly outside the class , So we need to provide an interface for out of class access , Original version as follows :

But when multiple threads access this interface at the same time , There is a thread safety problem at this time , We need to protect sig This critical resource , So lock critical resources , The lock used must also be static Embellished

![]()

Now when a thread finally applies for a lock , But go in and have a look , Find out sig It has been initialized by other threads , Applying for a lock is superfluous , So we best Before applying for a lock , Add another judgment , First judge whether it is empty , Re apply for .

3、 ... and 、 Singleton mode test
We create in the main thread 5 Threads , every other 1s Print the address of the currently obtained object once , And threads ID

The test results are as follows :

Four 、 expand : Starving model ( Brief introduction )
Hungry man mode is created when the program starts running , The difference lies in the way the object is declared .
No * No. means to open up on the stack , At this time, the object will be allocated space when it is created

In the interface function , There is no need to judge whether it is empty , Just go back

Return value plus & The reason is that Prevent implicit calls to copy constructors
边栏推荐
- Visualisation de l'ensemble de données au format yolov5 (fichier labelme json)
- 缺少库while loading shared libraries: libisl.so.15: cannot open shared object file: No such file
- Machine learning process and method
- How to refresh the opening amount of Oracle ERP
- y54.第三章 Kubernetes从入门到精通 -- ingress(二七)
- How can retail enterprises open the second growth curve under the full link digital transformation
- Processing of tree structure data
- 机器学习流程与方法
- Socket编程
- Coroutinecontext in kotlin
猜你喜欢

Servlet中数据传到JSP页面使用el表达式${}无法显示问题

PyTorch 卷积网络正则化 DropBlock

微信小程序開發工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理問題
![[shutter] pull the navigation bar sideways (drawer component | pageview component)](/img/6f/dfc9dae5f890125d0cebdb2a0f4638.gif)
[shutter] pull the navigation bar sideways (drawer component | pageview component)

8 free, HD, copyright free video material download websites are recommended

y54.第三章 Kubernetes从入门到精通 -- ingress(二七)

Bottleneck period must see: how can testers who have worked for 3-5 years avoid detours and break through smoothly

The technology boss is ready, and the topic of position C is up to you
![[leetcode] 797 and 1189 (basis of graph theory)](/img/2a/9c0a904151a17c2d23dea9ad04dbfe.jpg)
[leetcode] 797 and 1189 (basis of graph theory)
![[shutter] bottom navigation bar implementation (bottomnavigationbar bottom navigation bar | bottomnavigationbaritem navigation bar entry | pageview)](/img/41/2413af283e8f1db5d20ea845527175.gif)
[shutter] bottom navigation bar implementation (bottomnavigationbar bottom navigation bar | bottomnavigationbaritem navigation bar entry | pageview)
随机推荐
What are MySQL locks and classifications
Return a tree structure data
[Flutter] dart: class;abstract class;factory;类、抽象类、工厂构造函数
Summary of ES6 filter() array filtering methods
Button button adaptive size of wechat applet
Qt之QComboBox添加QCheckBox(下拉列表框插入复选框,含源码+注释)
Socket programming
Return the only different value (de duplication)
[Yu Yue education] reference materials of love psychology of China University of mining and technology
Redis:Redis的简单使用
Bottleneck period must see: how can testers who have worked for 3-5 years avoid detours and break through smoothly
What are the key points often asked in the redis interview
udp接收队列以及多次初始化的测试
线程安全的单例模式
The Sandbox阐释对元宇宙平台的愿景
机器学习笔记(持续更新中。。。)
微信小程序開發工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理問題
stm32F407-------ADC
What are the differences between software testers with a monthly salary of 7K and 25K? Leaders look up to you when they master it
Su Shimin: 25 principles of work and life