找传奇、传世资源到传世资源站!

python 单例模式(入门级)

8.5玩家评分(1人评分)
下载后可评
介绍 评论 失效链接反馈

#!/usr/bin/python# -*- coding: utf-8 -*-import threadingdef synchronized(func): func.__lock__=threading.Lock() def synced_func(*args,**kws): with func.__lock__ : return func(*args,**kws) return synced_funcclass Singleton(object): instance=None @synchronized def __new__(cls,*args,**kw): if cls.instance is None: cls.instance = object.__new__(cls, *args, **kw) return cls.instance def __init__(self, num): self.a = num 5 def printf(self): print(self.a)def worker(i): single_test = Singleton(i) single_test.printf() print "id----> %s" % id(single_test)if __name__ == "__main__": task_list = [] for i in range(3): t = threading.Thread(target=worker,args=(i,)) task_list.append(t) for one in task_list: one.start() for one in task_list: one.join()

评论

发表评论必须先登陆, 您可以 登陆 或者 注册新账号 !


在线咨询: 问题反馈
客服QQ:174666394

有问题请留言,看到后及时答复