pythonmultithreadingsocketsclient-server

How to cleanly kill a "while true" thread in python when this thread was created inside another thread?


In the project I'm working now, I have the task to create a server-client program in python. The idea is to have "n" remote devices connected to a server. Through socket programming, the server will listen for requests to connect done by the devices and create a thread for each one. Each thread will be responsible in receiving data from the devices. Basically, the program works like this:

Right now, everything works fine, except that when there is a socket error or timeout, even though the loop of the thread is broken using the "break" command, the thread is keeped alive. I have a print in the code that keeps counting the active threads using "threading.active_count()" command. Each time there is a connection drop, the number increases. I think this is bad in terms of performance/memory of the system. When searching for a solution, I found the "thread.join()" command, but by my understaning this will block the "listener" thread. I need the thread to continously keep listening for new clients. Is there any way of cleanly kill a thread? Is garbage collector good for this?


Solution

  • Ok, I figured it out, It seems that the socket.accept() doesn't inherit the configurations of the socket created in client side. I needed to set a timeout on the server side. I misread the documentation. Thank you anyway.