Python Forum

Full Version: Quitting multiple threads
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi there.

I'm looking into thread.interrupt_main() as a way to exit a thread and close an app irrespective of other threads running.

But, if I've started my app off with:
threads=[threading.Thread(target=func) for func in [ThreadOne, ThreadTwo$
[th.start() for th in threads]
[th.join() for th in threads]

Where does the keyboard handling code go? I don't have a loop anywhere in the main thread anymore?

Many thanks.
Use threading.Event()
Share this object across all threads you want to close. Instead of using while True, use while not event.is_set():

In the manager thread you set the event: event.set()
Then all threads which are still executing, leaves the loop.

Other possible way are signals. I never used them for threads...
(Oct-16-2018, 09:14 PM)MuntyScruntfundle Wrote: [ -> ]
  [th.start() for th in threads]
  [th.join() for th in threads]

Please, don't replace for loops with parasitic list comprehensions with side effects.

This code just starts threads
for th in threads:
    th.start()
This code starts threads - and builds a list of None values which is immediately discarded.
  [th.start() for th in threads]
While many adopted this style believing it to be Pythonic - it is essentially un-Pythonic, since you implicitly produces parasitic side effect.

Let me demonstrate on a simple function that does nothing
Output:
In [7]: def demo(): ...: pass ...: ...: In [8]: %%timeit ...: for _ in range(10000): ...: demo() ...: 698 µs ± 5.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [9]: %timeit [demo() for _ in range(10000)] 838 µs ± 12.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
As you can clearly see, using comprehension instead of a loop (less sexy Naughty , I know) costs you about 12% overhead Hand . Where did the resource go? It was wasted managing the redundant temporary list Doh .

Do you comprehend Cool ?