Friday 24 January 2014

How to use Threading in Python


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.currentThread(): Returns the number of thread objects in the caller's thread control.
  • threading.enumerate(): Returns a list of all thread objects that are currently active.

·     In addition to the methods, the threading module has the Thread class that implements threading. The methods provided by the Thread class are as follows:

  • 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.

    Example
#!/usr/bin/python

import threading
import time

exitFlag = 0

class StartThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print "Starting " + self.name
        check_time(self.name, self.counter, 5)
        print "Exiting " + self.name

def check_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            thread.exit()
        time.sleep(delay)
        print "%s: %s" % (threadName, time.ctime(time.time()))
        counter -= 1

# Create new threads
thread1 = StartThread(1, "Thread-1", 1)
thread2 = StartThread(2, "Thread-2", 2)

# Start new Threads
thread1.start()
thread2.start()

print "Exiting Main Thread"

When the above code is executed, it produces the following result: 
Starting Thread-1
Starting Thread-2
Exiting Main Thread
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-1
Thread-2: Thu Mar 21 09:10:08 2013
Thread-2: Thu Mar 21 09:10:10 2013
Thread-2: Thu Mar 21 09:10:12 2013
Exiting Thread-2
Thanks Guys

No comments:

Post a Comment