Synchronizing Threads


threadLock = threading.Lock() . . . threadLock.acquire() print_time(self.name, self.counter, 3) threadLock.release()

The threading module provided with Python includes a simple-to-implement locking mechanism that will allow you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock.

Once the new lock object has been created, you can force threads to run synchronously by calling the acquire(blocking) method. The optional blocking parameter enables you to control whether the thread will wait to acquire the lock. If blocking is set to 0, the thread will return immediately with a 0 value if the lock cannot be acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread will block and wait for the lock to be released.

When you are finished with the lock, the lock is released by calling the release() method of the new lock object.

import threading import time 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 #Get lock to synchronize threads         threadLock.acquire()         print_time(self.name, self.counter, 3) #Free lock to release next thread         threadLock.release() def print_time(threadName, delay, counter):     while counter:         time.sleep(delay)         print "%s: %s" % (threadName, \             time.ctime(time.time()))         counter -= 1 threadLock = threading.Lock() threads = [] #Create new threads thread1 = newThread(1, "Thread01", 1) thread2 = newThread(2, "Thread02", 2) #Start new Threads thread1.start() thread2.start() #Add threads to thread list threads.append(thread1) threads.append(thread2) #Wait for all threads to complete for t in threads:     t.join() print "Exiting Main Thread"


sync_thread.py

Starting Thread01 Starting Thread02 Thread01: Tue Jun 20 10:06:24 2006 Thread01: Tue Jun 20 10:06:25 2006 Thread01: Tue Jun 20 10:06:26 2006 Thread02: Tue Jun 20 10:06:28 2006 Thread02: Tue Jun 20 10:06:30 2006 Thread02: Tue Jun 20 10:06:32 2006 Exiting Main Thread


Output from sync_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