Thread-Safe single-case mode

Source: Internet
Author: User

Singleton mode is to ensure that a class has only one instance and is easy to access outside. So generally only the constructor, copy function, destructor, assignment function, variable name into private. You can then use a Get function to access the provided interface. Consider thread safety and lock it up.

First, lazy mode:

1. Lazy mode for static member instances:

Class Singleton{private:    static singleton* m_instance;    Singleton () {}public:    static singleton* getinstance ();}; singleton* singleton::getinstance () {    if (NULL = = m_instance)    {        Lock ();        if (m_instance = = NULL)        {            m_instance = new Singleton;        }        UnLock ();    }    return m_instance;}

2. Lazy mode of internal static instance

Class Singletoninside{private:    singletoninside () {}public:    static singletoninside* getinstance ()    {        Lock ();         static Singletoninside instance;        UnLock ();         return instance;}     ;

Second, a hungry man mode

Static instance initialization is initiated by the main thread in a single-threaded manner before the program starts to enter the main function, without worrying about multithreading issues. This mode should be used to avoid frequent lock contention when performance requirements are high.

Class Singletonstatic{private:    static const singletonstatic* m_instance;    Singletonstatic () {}public:    static const singletonstatic* getinstance ()    {        return m_instance;    }};


Thread-Safe single-case mode

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.