python多线程threading.Lock锁用法实例
2015-06-30 09:43
579 查看
本文实例讲述了python多线程threading.Lock锁的用法实例,分享给大家供大家参考。具体分析如下:
python的锁可以独立提取出来
锁定方法acquire可以有一个超时时间的可选参数timeout。如果设定了timeout,则在超时后通过返回值可以判断是否得到了锁,从而可以进行一些其他的处理。
python的锁可以独立提取出来
mutex = threading.Lock() #锁的使用 #创建锁 mutex = threading.Lock() #锁定 mutex.acquire([timeout]) #释放 mutex.release()
锁定方法acquire可以有一个超时时间的可选参数timeout。如果设定了timeout,则在超时后通过返回值可以判断是否得到了锁,从而可以进行一些其他的处理。
#!/usr/bin/env python #coding=utf-8 import threading import time class MyThread(threading.Thread): def run(self): global num time.sleep(1) if mutex.acquire(1): num = num+1 msg = self.name+' set num to '+str(num) print msg mutex.release() num = 0 mutex = threading.Lock() def test(): for i in range(5): t = MyThread() t.start() if __name__ == '__main__': test() Thread-1 set num to 1 Thread-3 set num to 2 Thread-4 set num to 3 Thread-5 set num to 4 Thread-2 set num to 5
相关文章推荐
- Python_11-正则表达式
- compute the su procedure time with python
- Python定制类
- Python多重继承
- python面向对象 格式很重要
- Python 使用@property
- Python-lamada表达式
- python装饰器
- mac 配置Python集成开发环境
- Android.Ant.Python之批量打包(一)
- Python学习笔记 - map reduce
- Python学习笔记 - map reduce
- Python学习笔记 - 高阶函数
- Python学习笔记 - 高阶函数
- python实现的简单FTP上传下载文件实例
- python实现线程池的方法
- python实现在windows服务中新建进程的方法
- python实现的系统实用log类实例
- python实现DES加密解密方法实例详解
- Python实现高效求解素数代码实例