Search code examples
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:

  • When the program start, a "While true" thread (lets call it "listener") is created and awaits for the remote devices to request a connection.
  • This thread, after accepting the connections, will be responsible in creating "n" threads, one for each remote device. For example, if we have 6 devices we will have 6 threads that will be responsible in receiving data from the devices.
  • Each thread is also a "While true" thread because the devices will keep sending data indefinetely.
  • I want to kill the threads when there is a socket timeout or error. But I don't want to kill them all, just the thread of the device that lost connection or crashed. When the device is up again, I want to create a new thread for the device.

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.