Describing join(timeout=None)
-
The
joinmethod waits until:- The thread terminates
- Or a timeout occurs
- The
timeoutrepresents the seconds until timeout - In
t.join(), the main thread will be blocked until threadtfinishes executing - Then, the main thread waits until thread
thas finished - Once
tfinishes, then the main thread can resume execution - Specifically, the main thread starts executes code after
join - Essentially, the main thread is paused until thread
tfinishes
Caveats of join
- A thread cannot join itself
- A thread cannot join before it has
started - Note, the scheduling of threads is done by the OS
- Implying, the order in which threads are run is determined by the operating system
- Meaning, multiple runs will produce different orderings
- Each thread's order of execution will vary from run to run
Setup Code for join
# sleepy.py
>>> import logging
>>> from threading import Thread
>>> import time
>>> def sleepy():
... print('thread started')
... time.sleep(10)
... print('thread done')Example without join
>>> t = Thread(target=sleepy)
>>> t.start()
thread started
>>> print('main done')
main done
thread doneExample with join
>>> t = Thread(target=sleepy)
>>> t.start()
thread started
>>> t.join() # haults any further execution
thread done # until thread finishes
>>> print('main done') # now we can print
main doneReferences
Previous
Next