使用python写一个线程安全的单例模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# 使用python写一个线程安全的单例模式
# 参考:https://juejin.cn/post/6844903951624585229
import threading
import time
 
 
def synchronized(func):
    func.__lock__ = threading.Lock()
 
    def lock_func(*args, **kwargs):
        with func.__lock__:
            return func(*args, **kwargs)
 
    return lock_func
 
 
class Singleton(object):
    instance = None
 
    @synchronized
    def __new__(cls, *args, **kwargs):
        # type kwargs: object
        if cls.instance is None:
            time.sleep(0.5)
            cls.instance = super().__new__(cls)
        return cls.instance
 
 
class MyClass(Singleton):
    def __init__(self, a):
        self.a = a
 
 
def check(lst):
    for i in range(len(lst)):
        if i > 0 and id(lst[i]) != id(lst[i - 1]):
            return False
    return True
 
 
def test(n):
    def func():
        obj = Singleton(9)
        print(id(obj))
 
    for i in range(n):
        thread = threading.Thread(target=func)
        thread.start()
 
 
if __name__ == "__main__":
    test(10)
 
# 31744710112483174471011248
#
# 31744710112483174471011248
# 3174471011248
#
# 3174471011248
# 3174471011248
# 3174471011248
# 3174471011248
# 3174471011248

  

posted on   patton88  阅读(180)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
历史上的今天:
2019-08-10 Radmin自动登录器 v3.0

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示