美文网首页
python 单例代码块

python 单例代码块

作者: 夜空最亮的9星 | 来源:发表于2021-05-13 22:26 被阅读0次

    加锁

    但是使用类方式创建的单例,无法支持多线程,因此使用加锁的方式;

    未加锁部分并发执行,加锁部分串行执行,速度降低,但是保证了数据安全

    import threading
    class Singleton(object):
        _instance_lock = threading.Lock()
        def __init__(self):
            pass
    
        def __new__(cls, *args, **kwargs):
            if not hasattr(Singleton, "_instance"):
                with Singleton._instance_lock:
                    if not hasattr(Singleton, "_instance"):
                        Singleton._instance = object.__new__(cls)
            return Singleton._instance
    
    

    相关文章

      网友评论

          本文标题:python 单例代码块

          本文链接:https://www.haomeiwen.com/subject/maffjltx.html