Creating and Exiting Threads


class newThread (threading.Thread):     def __init__(self, threadID, name, counter):         self.threadID = threadID         self.name = name         self.counter = counter         threading.Thread.__init__(self) . . . . . if doExit:     thread.exit()

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 phrase. It is a little more complicated to implement; however, it provides the ability to better control and synchronize threads.

The threading module introduces a Thread class that represents a separate thread of execution. To implement a new thread using the threading module, first define a new subclass of the Thread class. Override the __init__(self [,args]) method to add additional arguments. 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() or run() methods.

import threading import thread import time doExit = 0 class newThread (threading.Thread):     def __init__(self, threadID, name, counter):         self.threadID = threadID         self.name = name         self.counter = counter         threading.Thread.__init__(self)     def run(self):         print "Starting " + self.name         print_time(self.name, self.counter, 5)         print "Exiting " + self.name def print_time(threadName, delay, counter):     while counter:         if doExit:             thread.exit()         time.sleep(delay)         print "%s: %s" % (threadName, \             time.ctime(time.time()))         counter -= 1 #Create new threads thread1 = newThread(1, "Thread01", 1) thread2 = newThread(2, "Thread02", 2) #Start new Threads thread1.start() thread2.run() while thread2.isAlive():     if not thread1.isAlive():         doExit = 1     pass print "Exiting Main Thread"


exit_thread.py

Starting Thread01 Starting Thread02 Thread01: Wed Jun 14 13:06:10 2006 Thread01: Wed Jun 14 13:06:11 2006 Thread02: Wed Jun 14 13:06:11 2006 Thread01: Wed Jun 14 13:06:12 2006 Thread01: Wed Jun 14 13:06:13 2006 Thread02: Wed Jun 14 13:06:13 2006 Thread01: Wed Jun 14 13:06:14 2006 Exiting Thread01 Thread02: Wed Jun 14 13:06:15 2006 Exiting Main Thread


Output from exit_thread.py code




Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net