如何在这个多线程TCPServer中在不同线程间共享数据?

20

我正在开发一个需要通过TCP传输数据的项目。使用ThreadedTCPServer,我已经可以做到这一点。服务器线程只需要读取传入的数据字符串并设置变量的值。与此同时,我需要主线程看到这些变量值的变化。以下是我迄今为止的代码,仅从ThreadedTCPServer示例中进行了修改:

import socket
import threading
import SocketServer

x =0

class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        data = self.request.recv(1024)
        # a few lines of code in order to decipher the string of data incoming
        x = 0, 1, 2, etc.. #depending on the data string it just received

class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    pass

if __name__ == "__main__":
    # Port 0 means to select an arbitrary unused port
    HOST, PORT = 192.168.1.50, 5000

    server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)

    # Start a thread with the server -- that thread will then start one
    # more thread for each request
    server_thread = threading.Thread(target=server.serve_forever)
    # Exit the server thread when the main thread terminates
    server_thread.daemon = True
    server_thread.start()
    print "Server loop running in thread:", server_thread.name

    while True:
        print x
        time.sleep(1)

    server.shutdown()

那么这个程序应该的工作方式是不断打印 x 的值,随着新消息的到来,x 的值应该发生变化。问题似乎在于主线程中打印的 x 不是在服务器线程中被赋予新值的相同的 x。我该如何从服务器线程更改主线程中 x 的值?


你尝试将打印语句放在工作线程中了吗? - didierc
1个回答

36

尝试在线程之间共享一个Queue

有用的资源

  • Python并发简介是David Beazley的演示文稿,提供了对多线程、线程通信和并发的良好简介。

1
谢谢,我知道我需要研究队列,但找不到好的资源。 - David Lopez
1
我提供的演示文稿涉及到队列,给出了一些简短的例子。这也有助于对这些概念的整体理解。 - Anton Strogonoff
3
对于那些被防火墙拦截了SlideShare的人,这是作者的页面:http://www.dabeaz.com/usenix2009/concurrent/。 - Ronan Paixão
2
这个问题有一个很好的最小工作示例。因此,有人应该使用这个最小工作示例提供答案,而不仅仅是链接到外部文档。 - buhtz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接