如何在这个线程TCPServer中的线程之间共享数据?

时间:2013-04-16 18:28:49

标签: multithreading python-2.6 tcpserver

我正在开发一个涉及通过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值?

1 个答案:

答案 0 :(得分:32)

尝试在您的主题之间共享Queue

有用的资源