Last active
June 25, 2020 16:41
-
-
Save kylemanna/df481b15aeec9ba3e8fc7c52c73daaf0 to your computer and use it in GitHub Desktop.
Do you _need_ to call threading.Thread.join() to clean-up threads on python if they exit cleanly?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
"""Do you _need_ to call threading.Thread.join() to clean-up threads on python if they exit cleanly? | |
""" | |
import threading | |
import time | |
def do_a_thing(idx): | |
print(f"starting {idx}") | |
time.sleep(1) | |
print(f"stopping {idx}") | |
time.sleep(1) | |
if __name__ == '__main__': | |
workers = [] | |
for i in range(100000): | |
t = threading.Thread(target=do_a_thing, args=(i,)) | |
workers.append(t) | |
t.start() | |
print(f"t=0 Threads {threading.active_count()} ->{threading.enumerate()}") | |
time.sleep(3) | |
print(f"t=3 Threads {threading.active_count()} ->{threading.enumerate()}") | |
[t.join() for t in workers] | |
print(f"t=final Threads {threading.active_count()} ->{threading.enumerate()}") | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
starting 0 | |
starting 1 | |
starting 2 | |
starting 3 | |
starting 4 | |
starting 5 | |
starting 6 | |
starting 7 | |
starting 8 | |
starting 9 | |
t=0 Threads 11 ->[<_MainThread(MainThread, started 140324786026304)>, <Thread(Thread-1, started 140324780418816)>, <Thread(Thread-2, started 140324701730560)>, <Thread(Thread-3, started 140324693337856)>, <Thread(Thread-4, started 140324684945152)>, <Thread(Thread-5, started 140324676552448)>, <Thread(Thread-6, started 140324668159744)>, <Thread(Thread-7, started 140324659767040)>, <Thread(Thread-8, started 140324651374336)>, <Thread(Thread-9, started 140324164859648)>, <Thread(Thread-10, started 140324156466944)>] | |
stopping 7 | |
stopping 4 | |
stopping 1 | |
stopping 2 | |
stopping 3 | |
stopping 0 | |
stopping 6 | |
stopping 5 | |
stopping 9 | |
stopping 8 | |
t=3 Threads 1 ->[<_MainThread(MainThread, started 140324786026304)>] | |
t=final Threads 1 ->[<_MainThread(MainThread, started 140324786026304)>] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment