简体   繁体   English

Python - 线程 - 我可以列出线程队列吗?

[英]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.

相关问题 在Python线程中,我如何跟踪线程的完成? - In Python threading, how I can I track a thread's completion? 为什么我只能启动一个线程(使用 python 线程模块)一次? - Why can I launch a thread (with the python threading module) only once? 如何使用 python 在 RabbitMQ 交换中列出或发现队列? - How can I list or discover queues on a RabbitMQ exchange using python? Python线程:使主线程报告进度 - Python threading: make the main thread report the progress 线程 Thread-2 中的异常:Traceback(最近一次调用最后一次)我无法使多线程工作 - Exception in thread Thread-2: Traceback (most recent call last) I can't make the multi threading work 用于无限数据输入的python线程和队列(流) - python threading and queues for infinite data input (stream) 如何在多线程情况下使用python线程锁定模块 - How can I use python threading lock module in multi-thread case 在哪里可以找到python低级线程API _thread扩展模块的源代码? - where can I find the source code for python Low-level threading API _thread extension module? python threading:如何中断主线程并使其执行其他操作 - python threading: how to interrupt the main thread and make it do something else 如何在 python 中为 class 制作线程 - How can make threading for class in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM