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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

django获取from表单multiple-select的value和id的方法

如下所示: <select id="host_list" name="host_list" multiple> {% for op in host_list %}...

Python 获得13位unix时间戳的方法

在python 开发web程序时,需要调用第三方的相关接口,在调用时,需要对请求进行签名。需要用到unix时间戳。 在python里,在网上介绍的很多方法,得到的时间戳是10位。而ja...

python获取本机所有IP地址的方法

python获取本机所有IP地址的方法

本文实例为大家分享了python获取本机所有IP地址的具体代码,供大家参考,具体内容如下 import socket # 查看当前主机名 print('当前主机名称为 : ' +...

python实现协同过滤推荐算法完整代码示例

python实现协同过滤推荐算法完整代码示例

测试数据 http://grouplens.org/datasets/movielens/ 协同过滤推荐算法主要分为: 1、基于用户。根据相邻用户,预测当前用户没有偏好的未涉及物品...

详解Python给照片换底色(蓝底换红底)

详解Python给照片换底色(蓝底换红底)

现在网上出现了很多在线换底色的网页版工具是这么做的呢?其实用Python就可以实现。 环境要求 Python3 numpy函数库 opencv库 安装 下载适应版本的numpy函数库...