您的位置:首页 > 编程语言 > Python开发

python核心编程-使用线程锁

2016-01-19 22:02 627 查看
#!/usr/bin/env python
# -*- coding: UTF-8 -*-

''' function :线程模块thread
使用锁机制,等待线程结束
仅练习'''

from time import sleep, ctime
import thread

loops = [4,2]
def loop(nloop, nsec, lock):
print 'start loop', nloop, 'at:', ctime()
sleep(4)
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()


输出:

D:\Python27\test>thread03.py

starting at: Tue Jan 19 21:54:02 2016

%s [0, 1]

start loopstart loop 01 at:at: Tue Jan 19 21:54:02 2016Tue Jan 19 21:54:02 2016

loop 0 done at: Tue Jan 19 21:54:06 2016

loop 1 done at: Tue Jan 19 21:54:06 2016

all DONE at: Tue Jan 19 21:54:06 2016

D:\Python27\test>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: