In Python's documentation (v3.8.2) on threading, there is this text (ch. 17): "Python’s Thread class supports a subset of the behavior of Java’s Thread class; currently, there are no priorities, no thread groups, and threads cannot be destroyed, stopped, suspended, resumed, or interrupted." I haven't been hampered by no means of prioritizing, or grouping threads, but that last bit, "cannot be destroyed, stopped, suspended, resumed, or interrupted" is an issue.
I have an application that starts one thread to post sensor-data to a queue, and another one to pull sensor data from that queue, then post it to a curses window. The trouble is, there are instances where thread pairs (they're always pairs in this case) get over-written with new threads, owing to configuration changes, etc. Until now, I have been deleting the thread objects under the foolish assumption that this action will result in the destruction of said threads. I have noticed some weird behaviour in the app, which now makes sense, as several threads are attempting to post data to the same curses window object.
Changing my approach, I will create several thread pairs, treat them as indestructible, update their configurations as needed... but how do I control their execution from the main thread? Is there a best practice? I'm thinking, create several pairs of template threads, start them, and use the threading.Condition() or the threading.Event() class to start/stop the code inside each thread running, but how do I pass information about what to do to each running thread? Since I have not done this, I'm learning mostly by the time-honoured tradition of rtfm; but, examples and a little guidance will help. Do I use threading.Event.is_set()? If so, how do I set/clear the internal flag from outside the thread? Are threading.Event() objects global, and hence visible to the threads, or do I need to make the Event() object one of the arguments of the function executed by the thread, then let the thread function evaluate the Event() and set/clear it in the main thread?
Of the unsupported operations, it’s only interrupt that you should want; Java has long deprecated the others as being impossible to use safely in general. Since Python lacks even the generic interrupt interface (except that an interrupt produces a KeyboardInterrupt
on the main thread only, which is not very useful), you have to avoid basic functions like time.sleep
in favor of versions that also detect an inter-thread signal. (In general, successful methods of killing a thread are also able to control it, since they involve getting the thread’s attention and then having it exit.)
Details:
Thread
object can’t kill it: threads are the roots for garbage collection.SIGPIPE
.