我想维护一些复杂的类的唯一对象,因此我用Google搜索了一些单例实现。
但是当我在两个过程中都创建了这个单例类的许多对象时,发现有些不合逻辑的东西。
我尝试了很多单例工具,例如:
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内存,因此我需要单例保证。