A single-instance mode for C + + thread safety

Source: Internet
Author: User

1. What is a singleton mode?

The singleton mode is one of the design patterns, the simplest and most commonly used pattern in the design pattern, which is used to ensure that the object instances of one class are only one in the application, that is, they are created only once. In actual development, we often encounter situations where only one instance is created, such as: Configuration file, log object, thread pool, cache, etc. In order to ensure consistency, these instances need to be created only once throughout the application, for example, if the log object is created multiple times, it is likely that the contents of the log are inconsistent, and sometimes some objects that consume too much resources are created many times to waste resources, such as the thread pool. Therefore, in order to guarantee the single case of the object, a singleton pattern appears.

2. How do I create a singleton mode in C + +?

There are two ways to create a singleton pattern, namely "a Hungry Man mode" and "lazy mode". Before explaining these two approaches, let's introduce a holistic approach to creating singleton patterns in OOP languages, whether C + + or Java:
Step1: Declares the constructor to be private.
Because when you create an object, you call the constructor of the class to complete the allocation of the object's memory space and the initialization of the member, so if you want to restrict the creation of the object, you should first prohibit the external object from calling the constructor, and this way you can restrict the creation of the object.
Step2: An object (instance) that declares a private static class in a class.
This example is the only instance that we need to get. The static type is because we need to get directly from the class without getting through the object because we cannot create an object. At the same time from the encapsulation point of view, we need to define a static type of interface to return this instance.
Step3: A case fetch function that defines the public type of a static type.
You can call this function directly from the class to get the instance defined in the class.
Here we explain the two separately.
Whether it is through the "a Hungry man mode" or "lazy mode" above the idea of the general same.

3. A hungry man mode.

A hungry man mode, very image, that is, when the class loading has created a class of instances, we use the interface directly to obtain this instance, so we can see that the A Hungry man mode is a thread-safe below is what I implemented in C + +:
#

Include <iostream>using namespace STD;classsingleton{Private: Singleton () {}//define constructors as private and avoid creating external objects directly. ~singleton () {DeleteSIG;}StaticSingleton *sig;//Declare a private static data member to be used as an instance of the sig.  Public:StaticSingleton *getinstance ()//Declare an interface of a static type to obtain an instance{returnSig }}; singleton* Singleton::sig =NewSingleton;//definition and initialization of instances outside of the classintMainvoid) {Singleton *MSG1 = singleton::getinstance ();//Create two instancesSingleton *MSG2 = Singleton::getinstance ();//Interpreting instances for equality    if(MSG1 = = MSG2)cout<<"Same instance!\n";Else        cout<<"Error in Creating single instance!\n";return 0;}
4. Lazy Mode

The whole design idea of the lazy model is the same as the A hungry man pattern, but the lazy pattern only gives the instance declaration in the class is not defined. So it is the thread that is unsafe when multiple threads are competing, so it is necessary to use the locking mechanism, which requires the cooperation of the operating system, and this does not give the thread safety of the lazy mode.

Include <iostream> usingnamespaceStdclasssingleton2{Private: Singleton2 () {}StaticSingleton2 *Sig;//Just give a statement Public:Staticsingleton2* getinstance ();}; singleton2* singleton2::getinstance () {if(Sig= = NULL) {Sig=NewSingleton2; }return Sig;} singleton2* Singleton2::Sig;//uninitialized, and a hungry man mode differences. int main (void) {Singleton2 *MSG1 = singleton2::getinstance ();//Create two instancesSingleton2 *MSG2 = Singleton2::getinstance ();//Interpreting instances for equality    if(MSG1 = = MSG2) cout <<"Same instance!\n";Elsecout <<"Error in Creating single instance!\n";return 0;}
5. The difference between the A hungry man and the lazy

A hungry man is the case of classes that have been completed at the time of class loading, so they are slower to load, but faster to run and thread safe.
The lazy mode is the opposite of the A Hungry man mode.
by Lingtao Kong in Nanjing 2015/04/15
http://blog.csdn.net/michael_kong_nju/article/details/45060527

A single-instance mode for C + + thread safety

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.