gpt4 book ai didi

python - 创建单例队列 Python

转载 作者:太空宇宙 更新时间:2023-11-04 09:58:34 24 4
gpt4 key购买 nike

我在我的项目中创建了一堆组件,每个组件都将在不同的线程中运行。
它们将通过 queue.Queue 进行通信。我想定义所有不同的队列,它们是扩展 queue.Queue 的类。它们中的每一个都是单例对象,因此不同的组件可以只导入该类并获取实例。

我将所有内容放在一个文件中:

from queue import Queue

class QueueAudio(Queue):

def __new__(cls, *args, **kwargs):
"""
Singleton Queue
"""
if '_inst' not in vars(cls):
cls._inst = object.__new__(cls, *args, **kwargs)
print('Creating {}'.format(cls.__name__))
return cls._inst

class AudioInput(object):

def __init__(self):
self.queue = QueueAudio()
print(self.queue)

def run(self):
self.queue.put('Input Audio')


class Interpretor(object):

def __init__(self):
self.queue = QueueAudio()
print(self.queue)

def run(self):
print(self.queue.get())

audio = AudioInput()
audio.run()
interpretor = Interpretor()
interpretor.run()

在两个组件(AudioInputInterpretor)的构造函数中,我打印对象,以确保它们相同。AudioInput 将一个字符串放入队列,Interpretor 读取它。然而,Interpretor 中的队列总是空的,导致程序永远挂起。这是程序的输出:

Creating QueueAudio
<__main__.QueueAudio object at 0x103234c18>
<__main__.QueueAudio object at 0x103234c18>

最佳答案

我通过使用另一种方法将我的类定义为单例来解决我的问题:

class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]

class QueueAudio(Queue, metaclass=Singleton):
pass

关于python - 创建单例队列 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44844013/

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