# The Threading Module in Python

PythonServer Side ProgrammingProgramming

The newer threading module included with Python 2.4 provides much more powerful, high-level support for threads than the thread module discussed in the previous section.

The threading module exposes all the methods of the thread module and provides some additional methods −

• threading.activeCount() − Returns the number of thread objects that are active.
• threading.enumerate() − Returns a list of all thread objects that are currently active.

• run()  − The run() method is the entry point for a thread.
• start()  − The start() method starts a thread by calling the run method.
• join([time])  − The join() waits for threads to terminate.
• isAlive()  − The isAlive() method checks whether a thread is still executing.
• getName()  − The getName() method returns the name of a thread.
• setName()  − The setName() method sets the name of a thread.

To implement a new thread using the threading module, you have to do the following −

• Define a new subclass of the Thread class.
• Then, override the run(self [,args]) method to implement what the thread should do when started.

Once you have created the new Thread subclass, you can create an instance of it and then start a new thread by invoking the start(), which in turn calls run() method.

## Example

#!/usr/bin/python
import time
exitFlag = 0
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
print_time(self.name, 5, self.counter)
print "Exiting " + self.name
while counter:
if exitFlag:
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
print "Exiting Main Thread"

When the above code is executed, it produces the following result −

Starting Thread-1
Thread-1: Thu Mar 21 09:10:03 2013
Thread-1: Thu Mar 21 09:10:04 2013
Thread-2: Thu Mar 21 09:10:04 2013
Thread-1: Thu Mar 21 09:10:05 2013
Thread-1: Thu Mar 21 09:10:06 2013
Thread-2: Thu Mar 21 09:10:06 2013
Thread-1: Thu Mar 21 09:10:07 2013
Exiting Thread-2