Python for thread-safe singleton mode

Source: Internet
Author: User

Singleton mode is a common design pattern that is designed to ensure that only one instance of a class exists. A singleton can come in handy when you want the entire system to have only one instance of a class.

For example, the configuration information of the server is written in a file online.conf, the client reads the contents of the configuration file through a config class. If the content of the configuration file needs to be used in many places during the run of the program, an instance of config will be created for each invocation of the configuration file, which results in an instance object with more than one config in the system, and we have wasted a lot of memory doing the same thing in the case of a lot of configuration file contents. In fact, for the Config class we only need one instance object when the program is running, and the singleton mode is the best choice.

Python's module is a natural singleton pattern, where we use decorators to implement a singleton pattern, the following is the code implementation

def Singleton (CLS):     = {}    def get_instance (*args, * *kw)        :if not in Instances:            = CLS (*args, * *kw        )return  instances[cls    ]  return Get_instance

The code is also simple, passing the class into the singleton decorator, if the class has not yet generated an instance (the class does not exist in instances), then a new instance is generated and recorded in instances. If the class already exists in the instances, return to instance instances[cls] directly.

So is this code perfect? The answer is no, this code is not thread-safe. In order for thread safety to be used in conjunction with locks, only the thread that holds the lock can continue to access the singleton instance, it seems that we need to write a decorator to implement thread safety, the following is the complete code implementation and simple multithreaded test cases.

#!/usr/bin/python#-*-coding:utf-8-*-ImportThreadingdefsynchronized (func): Func.__lock__=Threading. Lock ()defSynced_func (*args, * *KWS): with Func.__lock__:            returnFunc (*args, * *KWS)returnSynced_funcdefSingleton (CLS): Instances={} @synchronizeddefGet_instance (*args, * *kw):ifCls not inchInstances:instances[cls]= CLS (*args, * *kw)returnInstances[cls]returnget_instancedefworker (): Single_test=Test ()Print "ID---->%s"%ID (single_test) @SingletonclassTest (): a= 1if __name__=="__main__": Task_list= []     forOneinchRange (30): T= Threading. Thread (target=worker) Task_list.append (t) forOneinchTask_list:one.start () forOneinchTask_list:one.join ()

Python for thread-safe singleton 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.