gpt4 book ai didi

python - python中单例类的对象有不同的id

转载 作者:行者123 更新时间:2023-12-01 07:43:16 24 4
gpt4 key购买 nike

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

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

我尝试过很多单例工具,一个例子:

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内存,所以需要单例保证。

最佳答案

您可以尝试使用 handy-decorators
有一个 singleton 装饰器可以帮助您。

关于python - python中单例类的对象有不同的id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56583274/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com