18.4 thread模块
import thread
from time import ctime, sleep
loops = [4, 2]
def loop(nloop, nsec, lock):
print 'start loop ', nloop, ' at: ', ctime()
sleep(nsec)
print 'loop ', nloop, ' done at: ', ctime()
lock.release()
def main():
print 'starting at: ', ctime()
locks = []
nloops = range(len(loops))
for i in nloops:
lock = thread.allocate_lock()
lock.acquire()
locks.append(lock)
for i in nloops:
thread.start_new_thread(loop, (i, loops[i], locks[i]))
for i in nloops:
while locks[i].locked():
pass
print 'all DONE at: ', ctime()
main()
我们先调用thread.allocate_lock()函数创建一个锁的列表,并分别调用各个锁的acquire()函数获得锁。获得锁表示"把锁锁上"。
在线程结束的时候,线程要自己去做解锁操作。最后一个循环只是坐在那一直等,直到两个锁都被解锁为止才继续进行。