线程锁在单例模式中的应用
多个线程在执行过程中会因为竞争同一个资源而产生线程冲突,造成死锁,从而引出线程锁这个概念
先拿到锁再执行业务操作:
当然我对这一块了解的还不透彻,只是了解在不加锁的多线程情况下,会破坏单例模式,所以就有了下面这一段
1 import time 2 import threading 3 4 5 def decorator(func): 6 lock = threading.Lock() 7 8 def wrapper(*args, **kwargs): 9 with lock: 10 func(*args, **kwargs) 11 12 return wrapper 13 14 15 class Singleton(type): 16 def __init__(self, *args, **kwargs): 17 super(Singleton, self).__init__(*args, **kwargs) 18 self._instance = None 19 20 @decorator 21 def __call__(self, *args, **kwargs): 22 if self._instance is None: 23 time.sleep(1) 24 self._instance = super(Singleton, self).__call__(*args, **kwargs) 25 return self._instance 26 27 28 class Valley(metaclass=Singleton): 29 ... 30 31 32 def create(): 33 v = Valley() 34 print(id(v)) 35 36 37 if __name__ == '__main__': 38 for i in range(5): 39 t = threading.Thread(target=create) 40 t.start()
output:
140709207779456
140709207779456
140709207779456
140709207779456
140709207779456
希望看到的人能多给我讲讲线程锁的应用场景,最后愿口罩下的我们、裁员下的我们,每天都有盼头