python多线程threading.Lock锁用法实例

yipeiwu_com5年前Python基础

本文实例讲述了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基于mysql实现的简单队列以及跨进程锁实例详解

通常在我们进行多进程应用开发的过程中,不可避免的会遇到多个进程访问同一个资源(临界资源)的状况,这时候必须通过加一个全局性的锁,来实现资源的同步访问(即:同一时间里只能有一个进程访问资源...

Python模块搜索路径代码详解

简述 由于某些原因,在使用 import 时,Python 找不到相应的模块。这时,解释器就会发牢骚 - ImportError。 那么,Python 如何知道在哪里搜索模块的路径呢?...

Python 比较两个数组的元素的异同方法

通过set()获取两个数组的交/并/差集: print set(a).intersection(set(b)) # 交集 print set(a).union(set(b)) # 并...

Python中出现IndentationError:unindent does not match any outer indentation level错误的解决方法

Python中出现IndentationError:unindent does not match any outer indentation level错误的解决方法

今天在网上copy的一段代码,代码很简单,每行看起来该缩进的都缩进了,运行的时候出现了如下错误:  【解决过程】  1.对于此错误,最常见的原因是,的确没有缩进。...

Window10+Python3.5安装opencv的教程推荐

Window10+Python3.5安装opencv的教程推荐

1.确定Python版本,电脑64位或者32位 打开cmd(window键+R,输入cmd就出现),在命令行输入:打开cmd(window键+R,输入cmd就出现),在命令行输入:pyt...