我是 python 多线程的新手,对下面的代码感到困惑:
#!/usr/bin/env python
import thread
from time import sleep, ctime
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()
if __name__ == '__main__':
main()
当我尝试运行时,我得到了以下结果
starting at: Fri Aug 03 17:07:20 2012
start loopstart loop 01 at:at: Fri Aug 03 17:07:20 2012Fri Aug 03 17:07:20 20
12
loop 1 done at: Fri Aug 03 17:07:22 2012
loop 0 done at: Fri Aug 03 17:07:24 2012
all done at: Fri Aug 03 17:07:24 2012
如您所见,这两个线程的“开始”输出混淆了,我想有一些冲突,但我不明白细节以及如何解决它,谁能帮助我?谢谢。