标签:__name__ task [] singleton target work thread tar class
import threading
# 装饰器
def synchronized(func):
func.__lock__ = threading.Lock()
def synced_func(*args, **kws):
with func.__lock__:
return func(*args, **kws)
return synced_func
# 使用修饰器来实现单例模式
def singleton(cls):
instances = {}
@synchronized
def get_instance(*args, **kw):
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return get_instance
def worker():
single_test = Test()
print("id----> %s" % id(single_test))
@singleton
class Test(object):
a = 1
if __name__ == "__main__":
task_list = []
for one in range(5):
t = threading.Thread(target=worker)
task_list.append(t)
for one in task_list:
one.start()
for one in task_list:
one.join()
标签:__name__ task [] singleton target work thread tar class
原文地址:https://www.cnblogs.com/apollo1616/p/10347052.html