VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > python入门 >
  • python入门教程之Python中的单例模式如何正确运用?本文详解(3)

上述代码中定义了singleton类装饰器,装饰器在预编译时就会执行,利用这个特性,singleton类装饰器中替换了类原本的__new__与

__init__方法,使用singleton_new方法进行类的实例化,在singleton_new方法中,先判断类的属性中是否存在__it__属性,以此来判断

是否要创建新的实例,如果要创建,则调用类原本的__new__方法完成实例化并调用原本的__init__方法将参数传递给当前类,从而完成单

例模式的目的。

这种方法让单例类可以接受对应的参数但面对多线程同时实例化还是可能会出现多个实例,此时加上线程同步锁则可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def singleton(cls):
    cls.__new_original__ = cls.__new__
    @functools.wraps(cls.__new__)
    def singleton_new(cls, *args, **kwargs):
        # 同步锁
        with threading.Lock():
            it = cls.__dict__.get('__it__')
            if it is not None:
                return it
            
            cls.__it__ = it = cls.__new_original__(cls, *args, **kwargs)
            it.__init_original__(*args, **kwargs)
            return it
 
    cls.__new__ = singleton_new
    cls.__init_original__ = cls.__init__
    cls.__init__ = object.__init__
    return cls

是否加同步锁的额外考虑

如果一个项目不需要使用线程相关机制,只是在单例化这里使用了线程锁,这其实不是必要的,它会拖慢项目的运行速度。

阅读CPython线程模块相关的源码,你会发现,Python一开始时并没有初始化线程相关的环境,只有当你使用theading库相关功能时,

才会调用PyEval_InitThreads方法初始化多线程相关的环境,代码片段如下(我省略了很多不相关代码)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
static PyObject *
thread_PyThread_start_new_thread(PyObject *self, PyObject *fargs)
{
    PyObject *func, *args, *keyw = NULL;
    struct bootstate *boot;
    unsigned long ident;
    
    // 初始化多线程环境,解释器默认不初始化,只有用户使用时,才初始化。
    PyEval_InitThreads(); /* Start the interpreter's thread-awareness */
    // 创建线程
    ident = PyThread_start_new_thread(t_bootstrap, (void*) boot);
    
    // 返回线程id
    return PyLong_FromUnsignedLong(ident);
}
相关教程