码迷,mamicode.com
首页 > 编程语言 > 详细

多线程实现单例模式

时间:2019-05-18 21:16:14      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:int   func   event   线程   图片   单例模式   none   init   bsp   

 

 

代码:

技术图片
import threading


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:
            cls.instance = super().__new__(cls)
        return cls.instance

    def __init__(self, num):
        self.a = num + 5

    def printf(self):
        print(self.a)


a = Singleton(3)
print(id(a))
b = Singleton(4)
print(id(b))
View Code

 

多线程实现单例模式

标签:int   func   event   线程   图片   单例模式   none   init   bsp   

原文地址:https://www.cnblogs.com/xuechengeng/p/10886935.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!