[英]Python - Threading - Can I make a list of thread Queues?
I'm making a threaded chat server and I need a way to send a message to all the clients. 我正在制作线程聊天服务器,我需要一种方法向所有客户端发送消息。 I could use a global queue but then only one of the threads handling the clients would be able to send the message.
我可以使用全局队列,但只有一个处理客户端的线程能够发送消息。 So I was wondering if its possible to create a separate queue object within each of the client threads and append them to a list so that I would be able to send the message to each client's queue.
所以我想知道是否可以在每个客户端线程中创建一个单独的队列对象并将它们附加到列表中,以便我能够将消息发送到每个客户端的队列。 Is this possible?
这可能吗?
clientqueues = [] #Global list of client queues
class ClientThread(threading.Thread):
def __init__(self):
myqueue = Queue.Queue() #Client queue
clientqueues.append(myqueue)
...
def MessageAllClients(message):
global clientqueues
for queue in clientqueues:
queue.put(message)
Would this work or am I going about this the wrong way? 这会有用吗?或者我是以错误的方式进行此操作?
Your approach is just fine. 你的方法很好。 The only thing I would change is making
clientqueues
a static member of ClientThread
rather than a global variable. 我唯一要做的就是让
clientqueues
成为ClientThread
的静态成员 ,而不是全局变量。
Queue只是一个对象(就像Python中的所有东西一样),因此制作它们的列表没有问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.