【问题标题】:Sending the same continuous updates to multiple threads spawned by another thread将相同的连续更新发送到另一个线程产生的多个线程
【发布时间】:2017-12-17 14:32:36
【问题描述】:

我正在努力解决这个问题,所以希望得到一些意见。

我计划让一个线程运行一个套接字服务器,它每秒检查新的客户端连接。如果找到,它将为该连接生成一个线程,并在客户端断开连接后关闭它。这是我的工作。

我想从主程序中获取信息传递给结束线程,以便每个客户端接收到相同的信息。我不能真正使用multiprocessing.Queue,因为这会在第一个线程使用它之后删除该项目(并且我不能在服务器线程中拦截它,因为更新将限制为每秒 1 次,并且主线程不会'不知道有多少个连接),那么有人有什么建议吗?

线程的布局有点像这样:

Main script (running many times per second)
    -server (running 1 time per second)
        -client (sending information as soon as it receives it, ideally in sync with the main script)
        -client
        -client

我想我可能会从服务器生成一个线程来接收输入,然后该线程将生成客户端线程并向每个线程发送不同的 Queue 项目,但听起来应该有一种不那么混乱的方式.

编辑:中间线程的想法行不通,不幸的是,您无法跨线程传递连接或队列。

【问题讨论】:

    标签: python multithreading


    【解决方案1】:

    经过多次尝试,我终于找到了一种可行的方法。由于连接不能跨线程传递,socket.accept 需要在客户端线程内完成。为了避免产生多个,循环会暂停,直到线程发回它有连接的消息。

    为了将相同的队列项目发送给每个队列,运行另一个线程来访问所有队列,因此它可以获取一个项目并复制它。由于队列列表一直在变化,因此必须在每次连接后重新创建。

    这里不是复制超过 100 行代码,而是伪代码的一般思想:

    sock = socket.connect()
    
    threads = []
    queues = []
    while True:
    
        #Start a client thread ready for connection
        #Make sure to empty the queue before receiving messages
        queues.append(Queue())
        threads.append(Thread(client_thread, (sock, queues[-1], main_queue)))
        threads[-1].start()
    
        #Start the middleman thread
        #It receives an input from one queue and sends it a list of other queues
        #Restart required when the number of threads changes
        middleman.quit()
        middleman = Thread(middleman_thread, (main_queue, queues))
        middleman.start()
    
        #Wait for connection to be made
        addr = queue.get()
        print '{}:{} connected.'.format(*addr)
    
        #Close any threads with disconnected clients
        for thread in threads:
            if not thread.isAlive():
                 del thread
                 del queue
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 2015-10-19
      相关资源
      最近更新 更多