线程锁在单例模式中的应用
  Hdj9iQhcP0rD 2023年11月02日 39 0

多个线程在执行过程中会因为竞争同一个资源而产生线程冲突,造成死锁,从而引出线程锁这个概念

先拿到锁再执行业务操作:

当然我对这一块了解的还不透彻,只是了解在不加锁的多线程情况下,会破坏单例模式,所以就有了下面这一段

 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

 希望看到的人能多给我讲讲线程锁的应用场景,最后愿口罩下的我们、裁员下的我们,每天都有盼头

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  2Fnpj8K6xSCR   2024年05月17日   107   0   0 Python
  xKQN3Agd2ZMK   2024年05月17日   75   0   0 Python
  fwjWaDlWXE4h   2024年05月17日   38   0   0 Python
  YpHJ7ITmccOD   2024年05月17日   40   0   0 Python
Hdj9iQhcP0rD