python 多线程|python多线程threading.Lock锁的使用例子

更新时间:2019-06-21    来源:python    手机版     字体:

【www.bbyears.com--python】

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

本文来源:http://www.bbyears.com/jiaocheng/55121.html

热门标签

更多>>

本类排行