Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

multithreading - How to share data between threads in this threaded TCPServer?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try sharing a Queue between your threads.

Useful resources


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...