How to share data between threads in this threaded TCPServer?

David Lopez picture David Lopez · Apr 16, 2013 · Viewed 69.6k times · Source

I'm working on a project which involves sending data over TCP. Using the ThreadedTCPServer I'm able to do that already. The server thread only needs to read incoming strings of data and set the value of variables. Meanwhile I need the main thread to see those variables changing value. Here's my code so far, just modified from the ThreadedTCPServer example:

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()

So the way this should work is that the program constantly prints the value of x, and as new messages come in the value of x should change. It seems the problem is that the x that it prints in the main thread is not the same x which is being assigned a new value in the server threads. How can I change the value of x in the main thread from my server thread?

Answer

Anton Strogonoff picture Anton Strogonoff · Apr 16, 2013

Try sharing a Queue between your threads.

Useful resources