0

I'm setting up a multithreaded python server, and I want to remove threads that have been inactive for n seconds.

  • Only clean way is that the threads terminates itself by detecting its inactivity or by checking a flag which is set from some activity monitoring thread if worker thread should terminate. – Michael Butscher Nov 07 '19 at 05:09
  • Are you trying to reimplement `concurrent.futures.ThreadPoolExecutor` yourself? – o11c Nov 07 '19 at 05:17
  • Does this answer your question? [How to set timeout on python's socket recv method?](https://stackoverflow.com/questions/2719017/how-to-set-timeout-on-pythons-socket-recv-method) – Artiom Kozyrev Nov 07 '19 at 06:15
  • @ArtiomKozyrev not quite, I need a way to monitor the activity of the thread and set an according dynamic timeout, so this wouldn't help. – James Dean Nov 07 '19 at 07:01
  • @o11 I don't think I am. – James Dean Nov 07 '19 at 07:02
  • @JamesDean What does "inactive" mean? No timers queued and no I/O during that time? Or are you trying to describe "unresponsive to friendly requests"? – o11c Nov 07 '19 at 07:54
  • @o11c no I/O, for example, if it were a chat app, if no message was sent from the client for a period of time, their respective thread on the server should be terminated. I hope that clarifies it. – James Dean Nov 07 '19 at 08:05
  • @JamesDean I'm not convinced that setting the timeout won't work, but if need be, you could always call `poll` before a nonblocking `recv`. – o11c Nov 07 '19 at 08:24

1 Answers1

0

The approach I can think of for this situation is that, you must have a daemon that would handle such threads. As much as possible, those threads should have been spawned by that daemon for easier thread tracking, as well as handling the timer for such threads.

If this is not the case (a separate program spawned the thread), you must have established a naming (or tracking) standard enabling you to determine which threads are under your program's scope, so they can be terminated by the daemon accordingly.