Nearby lessons

139 of 159

Python - Thread join(seconds) Method

📌 What You Will Learn
  • Understand the syntax of join(seconds)
  • Explain what t.join(5) means
  • Describe what happens when the timeout expires
  • Know that join(5) does not terminate the child thread
  • Compare join() with join(seconds)

join(seconds) Method

We can call the join() method with a time period also.

t.join(seconds)

In this case, the calling Thread waits only for the specified amount of time.

Simple Definition:

join(seconds) makes the calling Thread wait for a maximum of the specified number of seconds.

After the specified time is completed, the waiting Thread continues its execution even if the Child Thread has not yet completed.

Main Thread
     │
     ▼
Start Child Thread
     │
     ▼
t.join(seconds)
     │
     ▼
Wait Maximum
Specified Time
     │
     ▼
Timeout Completed
     │
     ▼
Main Thread Continues

Syntax of join(seconds)

The syntax is:

t.join(seconds)
Part Description
t Thread object
join() Method used to make the calling Thread wait
seconds Maximum time the calling Thread should wait

Example:

t.join(5)

This means that the calling Thread waits for Thread t for a maximum of 5 seconds.

Understanding join(5)

Consider:

t.join(5)

Suppose this statement is executed by the Main Thread.

The Main Thread waits for a maximum of five seconds.

There are two possibilities.

Case 1: Child Thread Completes Before 5 Seconds

Child Thread
     │
     ▼
Completes in 3 Seconds
     │
     ▼
join(5) Returns
     │
     ▼
Main Thread Continues

The Main Thread does not need to wait for the full five seconds if the Child Thread finishes earlier.

Case 2: Child Thread Does Not Complete Within 5 Seconds

Child Thread
     │
     ▼
Still Executing
After 5 Seconds

Main Thread
     │
     ▼
join(5)
     │
     ▼
Wait 5 Seconds
     │
     ▼
Timeout
     │
     ▼
Main Thread Continues

Child Thread
     │
     ▼
Continues Its Remaining Work

This second situation occurs in the document's example.

Program - join(seconds)

🐍Code Cell
1from threading import *
2import time
3 
4def display():
5 for i in range(10):
6 print("Seetha Thread")
7 time.sleep(2)
8 
9t = Thread(target=display)
10t.start()
11 
12t.join(5) # This line executed by Main Thread
13 
14for i in range(10):
15 print("Rama Thread")
Output
No output captured.

Output

Important Note About the Output

The output above follows the example given in the document.

However, this is a multithreaded program.

The exact ordering and timing can vary depending on thread scheduling and the system.

The important concept is:

Child Thread Starts
       │
       ▼
Main Thread Waits
Maximum 5 Seconds
       │
       ▼
5 Seconds Completed
       │
       ▼
Main Thread Resumes
       │
       ▼
Child Thread May Still
Be Running

Therefore, after the timeout, output from Rama Thread and the remaining Seetha Thread executions can occur while both threads are active.

Program Explanation

Step 1: Import Required Modules

from threading import *
import time

The threading module is used to create and manage Threads.

The time module is used for creating a delay with:

time.sleep()

Step 2: Create the Child Thread Function

def display():

The display() function contains the work to be performed by the Child Thread.


Step 3: Print the Message Repeatedly

for i in range(10):
    print("Seetha Thread")

The loop executes ten times.

Therefore, the Child Thread prints:

Seetha Thread

ten times.


Step 4: Pause the Child Thread

time.sleep(2)

After printing each message, the Child Thread waits for two seconds.

Therefore, the complete Child Thread requires approximately:

10 iterations × 2 seconds
          =
Approximately 20 seconds

Step 5: Create the Thread

t = Thread(target=display)

A Child Thread object is created.

The target of the Child Thread is:

display

Therefore, Thread t will execute the display() function.


Step 6: Start the Child Thread

t.start()

The Child Thread starts executing:

display()

It begins printing:

Seetha Thread

Step 7: Main Thread Calls join(5)

t.join(5)

This statement is executed by the Main Thread.

The Main Thread waits for Thread t for a maximum of five seconds.

But the Child Thread requires approximately twenty seconds to complete its full work.

Therefore:

Child Thread Total Work
≈ 20 Seconds

Main Thread Waiting Time
= 5 Seconds

The Main Thread does not wait until the Child Thread completes.

It waits only for the specified timeout.


Step 8: Main Thread Continues

for i in range(10):
    print("Rama Thread")

After waiting for five seconds, the Main Thread resumes execution.

It starts printing:

Rama Thread

ten times.

At this time, the Child Thread may still be executing because it has not completed its approximately twenty-second job.

Therefore, both Threads can continue executing after the five-second waiting period.

Why Does This Output Occur?

The document explains the output using the following points:

  1. The Child Thread requires approximately 20 seconds to finish because it prints ten times and waits two seconds after every print.
  2. The Main Thread waits only 5 seconds because of:
t.join(5)
  1. After five seconds, the Main Thread continues its execution.
  2. The Child Thread has not completed its full execution at this point.
  3. Therefore, after the waiting period, the Main Thread and Child Thread can both be active.
0 Seconds
    │
    ▼
Child Thread Starts
    │
    ▼
Main Thread Calls join(5)
    │
    ▼
Main Thread Waiting
    │
    │
    │ Child Thread Continues
    │
    ▼
Approximately 5 Seconds
    │
    ▼
join(5) Timeout
    │
    ▼
Main Thread Continues
    │
    ├──────────────► Rama Thread
    │
    ▼
Child Thread Still Running
    │
    └──────────────► Seetha Thread

Execution Timeline

The basic timing can be understood like this:

Time        Child Thread              Main Thread
-------------------------------------------------------

0 sec       Seetha Thread             start t
                                       │
                                       ▼
                                      join(5)

2 sec       Seetha Thread             Waiting

4 sec       Seetha Thread             Waiting

~5 sec      Still not finished        Timeout completed
                                       │
                                       ▼
                                      Main continues
                                       │
                                       ▼
                                      Rama Thread

6 sec       Seetha Thread             Main may continue

8 sec       Seetha Thread

...         ...

~20 sec     Child completes

The exact scheduling can vary, but the Main Thread does not wait for the Child Thread's full completion because the timeout is only five seconds.

Execution Flow - join(seconds)

Program Starts
      │
      ▼
Import threading
and time
      │
      ▼
Create display()
      │
      ▼
Create Child Thread
      │
      ▼
t.start()
      │
      ▼
Child Thread Starts
      │
      ▼
Print
"Seetha Thread"
      │
      ▼
sleep(2)
      │
      │
      ├────────────────────────┐
      │                        │
      ▼                        ▼
Child Thread             Main Thread
Continues                Calls join(5)
                              │
                              ▼
                       Wait Maximum
                         5 Seconds
                              │
                              ▼
                         Timeout Ends
                              │
                              ▼
                       Main Thread
                         Continues
                              │
                              ▼
                         Prints
                       "Rama Thread"
                              │
      ┌───────────────────────┘
      │
      ▼
Child Thread May
Still Be Executing
      │
      ▼
Child Thread Continues
Until Completion

join() vs join(seconds)

The main difference is the duration for which the calling Thread waits.

join() join(seconds)
Waits until the Thread completes. Waits only for the specified maximum number of seconds.
Main Thread resumes after Child Thread finishes. Main Thread resumes after the timeout if the Child Thread has not finished.
No timeout is specified. A timeout is specified.
The Child Thread is complete when join() returns normally. The Child Thread may still be running when join(seconds) returns because of timeout.

join() Example

t.start()

t.join()

print("Main Thread Continues")

Flow:

Start Child
    │
    ▼
join()
    │
    ▼
Wait
    │
    ▼
Wait
    │
    ▼
Child Completes
    │
    ▼
Main Continues

Here, there is no timeout.

join(seconds) Example

t.start()

t.join(5)

print("Main Thread Continues")

Flow:

Start Child
    │
    ▼
join(5)
    │
    ▼
Wait Maximum
5 Seconds
    │
    ▼
Timeout
    │
    ▼
Main Continues
    │
    ▼
Child May Still
Be Executing

Important Difference - join(5) Does Not Stop the Child Thread

A very important point is that:

t.join(5)

does not mean:

Stop Thread t after 5 seconds

It means:

Wait for Thread t
for maximum 5 seconds

After the timeout:

  • The Main Thread continues.
  • The Child Thread is not automatically terminated.
  • The Child Thread can continue until its work is completed.
join(5)
   │
   ▼
Waiting Timeout
   │
   ├────────► Main Thread Continues
   │
   └────────► Child Thread May Continue

Summary of Methods and Functions Covered So Far

The following methods and functions have been covered in the Multi Threading chapter up to this point.

Method / Function Purpose
current_thread() Returns the currently executing Thread object
name property Returns or sets the name of the Thread
ident Returns the identification number of a Thread
active_count() Returns the number of active Threads
enumerate() Returns a list of all active Threads
is_alive() Checks whether a Thread is currently executing
start() Starts a Thread
run() Contains the job executed by the Thread
join() Waits until the specified Thread completes
join(seconds) Waits only for the specified maximum amount of time

Complete Chapter Summary - Up to Part 6

Multi Tasking

  • Process Based Multi Tasking
  • Thread Based Multi Tasking

Thread Creation Methods

  • Creating a Thread without using any class
  • Creating a Thread by extending the Thread class
  • Creating a Thread without extending the Thread class

Thread Information

  • current_thread()
  • name property
  • ident

Thread Management

  • start()
  • run()
  • active_count()
  • enumerate()
  • is_alive()

Waiting Methods

  • join()
  • join(seconds)

Summary

Topic Description
join() Waits until another Thread completes.
join(seconds) Waits for a maximum specified amount of time.
t.join(5) Waits for Thread t for at most five seconds.
Timeout After the timeout, the calling Thread continues if the target Thread is still running.
Child Thread May continue executing after the calling Thread resumes.
Example Child Execution Approximately 20 seconds because of ten two-second sleeps.
Main Thread Waiting Only five seconds because join(5) is used.

Important Notes

  1. join(seconds) makes the calling Thread wait only for the specified maximum time.
  2. The syntax is t.join(seconds).
  3. Here, t is the Thread object.
  4. The seconds value specifies the maximum amount of time the calling Thread should wait.
  5. After the specified timeout, the waiting Thread continues execution automatically if the target Thread is still running.
  6. If the target Thread completes before the timeout, join(seconds) returns earlier.
  7. join(seconds) does not terminate the Child Thread.
  8. The Child Thread may continue executing after the Main Thread resumes.
  9. In the document's program, the Child Thread requires approximately twenty seconds because it executes ten iterations with a two-second sleep.
  10. The Main Thread waits only five seconds because t.join(5) is used.
  11. After approximately five seconds, the Main Thread starts printing Rama Thread even though the Child Thread may still be executing.
  12. join() waits until the Thread completes.
  13. join(seconds) waits only for the specified maximum time.
  14. After a join(seconds) timeout, both the Main Thread and Child Thread may continue executing concurrently.
  15. Because Thread scheduling is controlled by the runtime and operating system, the exact interleaving of output can vary.
📝 Key Takeaways
  • t.join(5) makes the main thread wait for at most 5 seconds
  • After the timeout the main thread continues even if the child is still running
  • join(seconds) does not terminate the child thread
  • join() waits indefinitely, join(seconds) waits only up to the timeout

🧠 Test Your Knowledge

15 Questions
Progress: 0 / 15