美文网首页
python 单例模式 线程安全

python 单例模式 线程安全

作者: 假程序员 | 来源:发表于2020-06-02 00:12 被阅读0次
    import threading
    
    _lock = threading.Lock()
    
    
    class Single(object):
        def __new__(cls, *args, **kwargs):
            if not hasattr(Single, "_instance"):
                with _lock:
                    if not hasattr(Single, "_instance"):
                        self = super(Single, cls).__new__(cls, *args, **kwargs)
                        setattr(Single, "_instance", self)
            return getattr(Single, "_instance")
    
    
    def func():
        print(Single())
    
    
    if __name__ == '__main__':
        thread_list = list()
        for _ in range(1, 10):
            _ = threading.Thread(target=func)
            _.start()
            thread_list.append(_)
    
        for _ in thread_list:
            _.join()
    
    

    相关文章

      网友评论

          本文标题:python 单例模式 线程安全

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