python - 单例类的对象在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>
解决方案
您可以尝试使用方便的装饰器。
有一个singleton
装饰器可以帮助你。
推荐阅读
- reactjs - 使用 React 和 Gatsby 传递道具
- laravel - 使用 nuxt js 和 laravel API 的安全问题
- serial-port - 无法调试 Windows 的虚拟串口驱动程序
- pandas - 如何只聚合一列 pandas python 2.7
- excel - 用于机器学习的 Excel 到 csv,找不到列
- machine-learning - 为什么在使用 Naive-Bayes 的 CategoricalNB 训练模型时会出现 IndexError?
- javascript - 如何使浏览器自定义样式 (Chrome) 在 Google Earth Web 上运行?
- java - 构造函数在一个简单的练习中未定义
- sql-server - SQL Server - 从加入的月份和年份获取当前月份的所有月份和年份数字
- javascript - 如何在 2021 年在 gatsby 中设置 google-analytics 和 cookie 同意?