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?
All static and controlled data is shared between threads. All other data can also be shared through arguments/parameters and through based references, as long as the data is allocated and is not freed until all of the threads have finished using the data.
You can protect data variables shared between threads using a threading. Lock mutex lock, and you can share data between threads explicitly using queue.
Threads are sometimes called lightweight processes because they have their own stack but can access shared data. Because threads share the same address space as the process and other threads within the process, the operational cost of communication between the threads is low, which is an advantage.
Try sharing a Queue
between your threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With