首页 > 解决方案 > 单例类的对象在python中有不同的id

问题描述

我想维护某个复杂类的唯一对象,所以我用谷歌搜索了一些单例实现。

但是当我在两个进程中创建这个单例类的许多对象时,发现一些不合逻辑的东西。</p>

我尝试了许多单例工具,一个例子:

import sys
from  multiprocessing import Pool

class Singleton(object):
    def __init__(self, cls):
        self._cls = cls
        self._instance = {}
    def __call__(self):
        if self._cls not in self._instance:
            self._instance[self._cls] = self._cls()
        return self._instance[self._cls]

@Singleton
class frame_feature_extractor(object):
    def __init__(self):
        pass


def func(idx_process):
    for idx in range(5):
        e = frame_feature_extractor()
        print('%d th object  in %d th process, id = %d' % (idx_process, idx, id(e)))



if __name__ == '__main__':
    #func(2)
    num_process = 2
    pool = Pool(num_process)
    for idx_process in range(num_process):
        print idx_process
        pool.apply_async(func, [idx_process])
    pool.close()
    pool.join()

我在 mac pro(python 版本为 2.7.15)中多次运行此代码,所有对象 id 都相同,输出如下:

0 th object  in 0 th process, id = 4509630096
0 th object  in 1 th process, id = 4509630096
0 th object  in 2 th process, id = 4509630096
0 th object  in 3 th process, id = 4509630096
0 th object  in 4 th process, id = 4509630096
1 th object  in 0 th process, id = 4509630096
1 th object  in 1 th process, id = 4509630096
1 th object  in 2 th process, id = 4509630096
1 th object  in 3 th process, id = 4509630096
1 th object  in 4 th process, id = 4509630096

然后我在centos中运行这段代码(python版本为2.7.5),不同进程中的对象有不同的id,但同一进程中的对象有相同的id,输出如下:

0 th object  in 0 th process, id = 140449211456784
0 th object  in 1 th process, id = 140449211456784
0 th object  in 2 th process, id = 140449211456784
0 th object  in 3 th process, id = 140449211456784
0 th object  in 4 th process, id = 140449211456784
1 th object  in 0 th process, id = 140449211456912
1 th object  in 1 th process, id = 140449211456912
1 th object  in 2 th process, id = 140449211456912
1 th object  in 3 th process, id = 140449211456912
1 th object  in 4 th process, id = 140449211456912

另外,我在ubuntu 18.04上试过,结果和centos一样,困扰我很久了。

实际应用场景是:这个对象需要占用过多的GPU内存,所以需要singleton保证。</p>

标签: pythonsingleton

解决方案


您可以尝试使用方便的装饰器
有一个singleton装饰器可以帮助你。


推荐阅读