![]() |
Thread control - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Thread control (/thread-31232.html) |
Thread control - dkinsler - Nov-29-2020 Hello. New to threading and appear to be loosing control of the threads and cant seem to figure out how to do this correctly. I have an app (main) that reads a bunch of sensors and sleeps for a few minutes at a time. I have network sessions coming in and my understanding is that needs to be in a continuous loop. So I made that its own thread. When a client connects, it starts up a thread for each client in a handler. The issue is I can not figure out how to close the child/grandchild threads. If I 'control + c' my main app, it still can take connections somehow. Any help you could sent me on how to do this properly would be greatly appreciated. The code I have (for threading) has been taken in snippits from other code I have found along the way. In the example code below, the counting in the while loop at the bottom simulates my sensor reading main loop. Im thinking, from what I have read, I need some way to send something to the threads to tell them to stop, so maybe a variable that can be passed to them that could control their while loop if they were a class instead of a def func. How could the main app know how many of the grandchild threads were created and have them exit? Currently, if I close out the main thread, the client threads stay open until I think the TCP session times out. If I try to rerun the app too soon, it tells me the ports are already open and fails. import socket import threading HEADER = 64 PORT = 5050 SERVER = socket.gethostbyname(socket.gethostname()) ADDR = (SERVER, PORT) FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT" tcount = 0 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDR) def handle_client(conn, addr): # print("[NEW CONNECTION] {%d} connected." % addr) connected = True while connected: msg_length = conn.recv(HEADER).decode(FORMAT) if msg_length: msg_length = int(msg_length) msg = conn.recv(msg_length).decode(FORMAT) if msg == DISCONNECT_MESSAGE: connected = False print("{%s}" % msg) conn.send("Msg received".encode(FORMAT)) conn.close() def listen(): global tcount server.listen() print("[LISTENING] Server is listening on {%s}" % SERVER) while True: conn, addr = server.accept() thread = threading.Thread(target=handle_client, args=(conn, addr)) thread.start() tcount = threading.activeCount() - 1 #print("[ACTIVE CONNECTIONS] {%d}" % tcount) try: print("[STARTING] server is starting...") t1 = threading.Thread(target=listen) t1.start() x = 1 while (x > 0): print(x) print("[ACTIVE CONNECTIONS] {%d}" % tcount) x = x + 1 except KeyboardInterrupt: t1.join() thread.join() |