Python随附的线程模块包括一个易于实现的锁定机制,可让您同步线程。通过调用Lock()方法创建一个新锁,该方法返回新锁。
新锁对象的acquire(blocking)方法用于强制线程同步运行。可选的阻塞参数使您可以控制线程是否等待获取锁。
如果将blocking设置为0,则如果无法获取锁,则线程立即返回0值,如果获取锁,则线程立即返回1。如果将阻塞设置为1,则线程将阻塞并等待释放锁。
新的锁对象的release()方法用于在不再需要时释放锁。
#!/usr/bin/python import threading import time class myThread (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 #获取锁以同步线程 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 = [] #创建新线程 thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # Start new Threads thread1.start() thread2.start() #获取锁以同步线程 threads.append(thread1) threads.append(thread2) #等待所有线程完成 for t in threads: t.join() print "Exiting Main Thread"
执行以上代码后,将产生以下结果-
Starting Thread-1 Starting Thread-2 Thread-1: Thu Mar 21 09:11:28 2013 Thread-1: Thu Mar 21 09:11:29 2013 Thread-1: Thu Mar 21 09:11:30 2013 Thread-2: Thu Mar 21 09:11:32 2013 Thread-2: Thu Mar 21 09:11:34 2013 Thread-2: Thu Mar 21 09:11:36 2013 Exiting Main Thread