Lesson 04
Join and Status
Use is_alive and join so the Python main thread can see whether a child is running and can wait at one line until that child finishes.
Use is_alive and join so the Python main thread can see whether a child is running and can wait at one line until that child finishes.
Example
import threading
import time
def squares(values):
time.sleep(0.05)
print([p * p for p in values])
worker = threading.Thread(target=squares, args=([1, 2, 3],), name="squares")
print("before", worker.is_alive(), threading.active_count())
worker.start()
print("started", worker.is_alive())
worker.join()
print("joined", worker.is_alive(), threading.active_count())Before start(), is_alive() is false and active_count() is 1. After start(), the child counts as active while the short sleep keeps it alive. join() pauses MainThread at that line until squares finishes, so the joined line runs only after [1, 4, 9] prints. join() orders the statements. A normal child is not discarded when main reaches its last line; the process still waits for that child. Use join() when later main-thread work must happen after the child.
Key takeaways
-
is_alive()is false beforestart()and after the child finishes -
is_alive()is true while that child is running -
active_count()includesMainThread -
join()pauses the caller until that child finishes -
Later statements in main run after
join()returns -
Next: Thread Locks — one thread at a time in a shared section
-
Previous: Class Threads
Loading playground…
Check your understanding
Join and Status Quiz
What does is_alive() return before start()?
1 / 10