Using the join() Method in Python Threads
Understand how the join()
method in Python’s thread class blocks the calling thread until the specified thread terminates. This method handles termination due to normal completion, unhandled exceptions, or optional timeouts. Learn about the syntax for using join()
and how it raises a RuntimeError
if misused, such as attempting to join the current thread or if the thread has not been started.
The join()
method in the thread class blocks the calling thread until the thread whose join()
method is called terminates. Termination may be normal, due to an unhandled exception, or until an optional timeout occurs. It can be called many times. A RuntimeError
is raised if an attempt is made to join the current thread or if the thread has not been started.
Syntax
Here is the syntax to use the join()
method:
Syntax
thread.join(timeout)
Parameters
timeout
− A floating point number specifying the timeout duration for which the thread is blocked.
The join()
method always returns None
. You must call is_alive()
after join()
to check if a timeout occurred. If the thread is still alive, the join()
call timed out. Without a timeout argument, the operation blocks until the thread terminates.
Example
Here is an example of using the join()
method:
Example
thread1.start()
thread2.start()
thread1.join()
thread2.join()
is_alive() method
This method checks if the thread is alive. It returns True
just before calling the run()
method and until just after the run()
method terminates.