简体   繁体   中英

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.

Queue只是一个对象(就像Python中的所有东西一样),因此制作它们的列表没有问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM