Saturday 19 December 2015

Python: Thread Join

‘join’ method blocks the calling thread until the thread whose join() method is called terminates.

Syntax
join(timeout=None)
Argument ‘timeout’ is optional. If you don’t specify timeout, the operation will block until the thread terminates. ‘timeout’ is a floating point number specifying a timeout for the operation in seconds.

Suppose you divided a big problem into small tasks, lets say one big problem is divided into 5 small tasks. To solve the whole problem. All the 5 tasks must be completed, one task may finishes immediately, other takes 5 minutes, and other may take 1 hour etc., Your program must wait until all the tasks finishes its execution. Here the join method comes into picture.

Without join method

MyThread.py
import threading
import time

class MyThread(threading.Thread):
 def run(self):
  print(threading.current_thread().getName()," Started")
  time.sleep(1)
  print(threading.current_thread().getName()," Finished")
  

task1 = MyThread(name="Thread_1")
task2 = MyThread(name="Thread_2")
task3 = MyThread(name="Thread_3")
task4 = MyThread(name="Thread_4")
task5 = MyThread(name="Thread_5")

task1.start()
task2.start()
task3.start()
task4.start()
task5.start()

print("Reading input from all 5 tasks and processing")

$ python3 MyThread.py 
Thread_1  Started
Thread_2  Started
Thread_3  Started
Thread_4  Started
Thread_5  Started
Reading input from all 5 tasks and processing
Thread_1  Finished
Thread_2  Finished
Thread_3  Finished
Thread_4  Finished
Thread_5  Finished

Observe the output, 'Reading input from all 5 tasks and processing' message printed before all the tasks completion. We can solve this problem by using join method.


MyThread.py
import threading
import time

class MyThread(threading.Thread):
 def run(self):
  print(threading.current_thread().getName()," Started")
  time.sleep(1)
  print(threading.current_thread().getName()," Finished")
  

task1 = MyThread(name="Thread_1")
task2 = MyThread(name="Thread_2")
task3 = MyThread(name="Thread_3")
task4 = MyThread(name="Thread_4")
task5 = MyThread(name="Thread_5")

task1.start()
task2.start()
task3.start()
task4.start()
task5.start()

task1.join()
task2.join()
task3.join()
task4.join()
task5.join()

print("Reading input from all 5 tasks and processing")

$ python3 MyThread.py 
Thread_1  Started
Thread_2  Started
Thread_3  Started
Thread_4  Started
Thread_5  Started
Thread_1  Finished
Thread_4  Finished
Thread_2  Finished
Thread_3  Finished
Thread_5  Finished
Reading input from all 5 tasks and processing





Previous                                                 Next                                                 Home

No comments:

Post a Comment