python 单例模式

python 单例模式

import threading
import time
class Singleton(object):
    _instance_lock = threading.Lock()
    init=False
    def __init__(self,a):
        if Singleton.init==True:
            return
        Singleton.init=True
        print(a)
        pass
    def __new__(cls, *args, **kwargs):
        if not hasattr(Singleton, "_instance"):
            with Singleton._instance_lock:
                if not hasattr(Singleton, "_instance"):
                    Singleton._instance = object.__new__(cls)  
        return Singleton._instance

import threading

def task(arg):
    obj = Singleton(arg)
    print(obj)

for i in range(10):
    t = threading.Thread(target=task,args=[i,])
    t.start()

 

posted @ 2021-09-04 14:40  绵绵01  阅读(30)  评论(0编辑  收藏  举报
levels of contents