将相同的连续更新发送到另一个线程生成的多个线程

问题描述 投票:0回答:1

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

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

我希望从主程序中获取传递给结束线程的信息,以便每个客户端都能收到相同的信息。我不能真正使用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项目,但听起来应该是一个不那么混乱的方式。

编辑:inbetween线程的想法不起作用,不幸的是你不能跨线程传递连接或队列。

python multithreading
1个回答
0
投票

经过多次尝试,我终于想出了一种可行的方法。由于连接不能跨线程传递,因此需要在客户端线程内完成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
© www.soinside.com 2019 - 2024. All rights reserved.