python多线程threading.Lock锁用法实例
2014-11-01 10:28
567 查看
本文实例讲述了python多线程threading.Lock锁的用法实例,分享给大家供大家参考。具体分析如下:
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程序设计有所帮助。
您可能感兴趣的文章:
相关文章推荐
- Python中的Module用法实例
- python函数参数*args**kwargs用法实例
- Python中__call__用法实例
- Python中函数的用法实例教程
- Python中函数的用法实例教程
- [zz]常见python正则用法实例
- Python基础之函数用法实例详解
- python的类变量和成员变量用法实例教程
- python的类变量和成员变量用法实例教程
- Python切片用法实例教程
- python函数参数*args**kwargs用法实例
- Python中zip()函数用法实例教程
- Python中apply函数的用法实例教程
- Python中正则表达式的用法实例汇总
- 用实例说明python的*args和**kwargs用法
- Python中apply函数的用法实例教程
- python中enumerate的用法实例解析
- Python切片用法实例教程
- Python迭代用法实例教程