+ 1
Killing threads seems hit or miss
When I’ve written threading.Threads in Python, getting them to die has seemed hit or miss. Usually, I try setting an attribute of the thread object as a condition variable for the thread’s loop, and then set it to False externally, but sometimes this doesn’t work from program to program. My guess is that there’s some type of scope or scope-like problem happening, but if so I don’t know how to avoid it. Would you suggest any guides or educational documentation for the threading module? Thanks.
4 Respuestas
+ 3
My first authoritative source is usually RealPython.
https://realpython.com/intro-to-JUMP_LINK__&&__python__&&__JUMP_LINK-threading/
My question is, why do you want to "kill" a thread? Are you talking about a "daemon" thread that is executing a background process? If not, then there could be other ways to organize the execution of different threads and the article gives a really good overview of the various techniques and tools available.
+ 1
Tibor Santa I reverse engineered Thread usage from another program and some help documentation years ago, and I never really understood executors, pipelines, or what a daemon thread was. I’ve got two processes that need to happen at the same time (usually one is a Tk mainloop), and when they are both done, the program needs to exit. But, what often seems to happen is, even after both tasks are complete, the interpreter hangs indefinitely. I’ll look into the resource you provided, it seems helpful. Thanks.
0
Wilbur Jaywright ,
Here's a site search for "threading" on python.org.
https://duckduckgo.com/?q=site%3Apython.org+threading
python.org is the official language-specification site, but the writing gets a bit arcane sometimes. I always look there first then other sites if needed. I agree that realpython.com has excellent writers. geekforgeeks.com is usually a good next try after that.
0
When working with threads in Python, managing thread termination can indeed be a bit tricky at times. Here are some suggestions and tips on properly handling thread termination in Python:
- Using a shared variable
- Make sure your thread periodically checks this shared variable during its operation so that it can gracefully exit when the variable is set to True.
- Calling the `join()` method on a thread object will block the calling thread until the thread whose `join()` method is called terminates.
- Ensure that access to shared variables between threads is thread-safe. You can use locks or other synchronization mechanisms to prevent data races and ensure proper thread safety.
- Avoid global variables
- In some cases, using a ThreadPoolExecutor from the `concurrent.futures` module can simplify thread management and termination. It provides higher-level abstractions for managing a pool of worker threads.
Thanks!