Friday, 11 December 2015

Python: First Threading Application

We can create custom thread by extending threading.Thread class. Following step-by-step procedure explains how to create a thread.

Step 1: Import threading module

Step 2: Inherit the class ‘threading.Thread’.

Step 3: Define ‘run’ method

Step 4: Instantiate the custom thread class and call start method.


MyThread.py
#Step 1: Import threading module
import threading
import time

#Step 2: Extend threading.Thread class
class MyThread(threading.Thread):
 #Step 3: Define run method
 def run(self):
  for i in range(1, 10): 
   print(threading.current_thread().getName(), i)
   time.sleep(1)

#Instantiate MyThread class
thread1 = MyThread(name="Producer")
thread2 = MyThread(name="Consumer")

#Call start method
thread1.start()
thread2.start()

$ python3 MyThread.py 
Producer 1
Consumer 1
Producer 2
Consumer 2
Producer 3
Consumer 3
Consumer 4
Producer 4
Consumer 5
Producer 5
Consumer 6
Producer 6
Consumer 7
Producer 7
Consumer 8
Producer 8
Consumer 9
Producer 9


Thread will start by calling its start() method. ‘start()’ method invoke run() method in a separate thread of control.



Previous                                                 Next                                                 Home

No comments:

Post a Comment