python核心编程-使用线程锁
2016-01-19 22:02
726 查看
#!/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>
相关文章推荐
- Python 5.4 定制类
- python核心编程-线程
- Python 生成的页面中文乱码问题
- python基础之字典
- python更改或者查看当前工作目录
- 使用PYTHON解析Wireshark的PCAP文件
- 八大排序算法的Python实现
- 八大排序算法的Python实现
- CAS单点登录python客户端分析
- 使用PYTHONPATH来使用其他版本的Django来启动
- Python3.4 IP查询(api)
- python 中 五种字典(dict)的遍历方法,实验法比较性能。
- python random.shuffle(随机打乱列表等) 和 random.random
- python实现一个朴素贝叶斯分类器
- 初学python--参数传递方式
- ubuntu14.04LTS下编译安装Open Babel和python语言绑定
- Python【基础第一篇】
- 【python】获取三维图形的某个截面
- webvtt字幕转srt字幕的python程序(附改名程序)
- Python-map()函数格式化不规则输入