Implement a New Thread Using the Threading Module
- Define a new subclass of the Thread class
- Override the __init__(self [, args]) method to add additional arguments
- Override the run(self [,args]) method to implement what the thread should do when it is started.
- When this is done, you can start a new thread by invoking the start method which will in turn call the run method
exit_flag = 0
def __init__(self, threadId, name, counter):
self.threadId = threadId
self.name = name
self.counter = counter
print("Starting " + self.name + "\n")
print_time(self.name, self.counter, 5)
print("Exiting " + self.name + "\n")
def print_time(threadName, delay, counter):
print("%s : %s" % (threadName, time.ctime(time.time())))
counter -= 1
# main program
if __name__ == '__main__':
# create two threads
thread1 = myThread(1, "thread-1", 1)
thread2 = myThread(2, "thread-2", 2)
print("Exiting main thread")
- The threading module is the preferred module for creating and managing threads.
- Each thread is represented by a class that extends the thread class and overrides its run method.
- Then this run method becomes the starting point of the thread.
- Calling the constructor of thread class is mandatory.
- Using it, we can redefine some properties like name or group of the thread.
- The thread is placed in active state at the call to start method and remains there until it ends the run method or you throw an unhandled exception
thread-1 : Sun Dec 2 22:11:04 2018
thread-2 : Sun Dec 2 22:11:05 2018
thread-1 : Sun Dec 2 22:11:05 2018
thread-1 : Sun Dec 2 22:11:06 2018
thread-2 : Sun Dec 2 22:11:07 2018
thread-1 : Sun Dec 2 22:11:07 2018
thread-1 : Sun Dec 2 22:11:08 2018
thread-2 : Sun Dec 2 22:11:09 2018
thread-2 : Sun Dec 2 22:11:11 2018
thread-2 : Sun Dec 2 22:11:13 2018
Exiting main thread