对python多线程中Lock()与RLock()锁详解

yipeiwu_com6年前Python基础

资源总是有限的,程序运行如果对同一个对象进行操作,则有可能造成资源的争用,甚至导致死锁

也可能导致读写混乱

锁提供如下方法:

1.Lock.acquire([blocking])

2.Lock.release()

3.threading.Lock() 加载线程的锁对象,是一个基本的锁对象,一次只能一个锁定,其余锁请求,需等待锁释放后才能获取

4.threading.RLock() 多重锁,在同一线程中可用被多次acquire。如果使用RLock,那么acquire和release必须成对出现,

调用了n次acquire锁请求,则必须调用n次的release才能在线程中释放锁对象

例如:

无锁:

#coding=utf8
import threading
import time

num = 0

def sum_num(i):
  global num
  time.sleep(1)
  num +=i
  print num

print '%s thread start!'%(time.ctime())

try:
  for i in range(6):
    t =threading.Thread(target=sum_num,args=(i,))
    t.start()

except KeyboardInterrupt,e:
  print "you stop the threading"

print '%s thread end!'%(time.ctime())

输出:

Sun May 28 20:54:59 2017 thread start!
Sun May 28 20:54:59 2017 thread end!
01
3
710
15

结果显示混乱

引入锁:

#coding=utf8
import threading
import time

num = 0

def sum_num(i):
  lock.acquire()
  global num
  time.sleep(1)
  num +=i
  print num
  lock.release()

print '%s thread start!'%(time.ctime())

try:
  lock=threading.Lock()
  list = []
  for i in range(6):
    t =threading.Thread(target=sum_num,args=(i,))
    list.append(t)
    t.start()

  for threadinglist in list:
    threadinglist.join()

except KeyboardInterrupt,e:
  print "you stop the threading"

print '%s thread end!'%(time.ctime())

结果:

Sun May 28 21:15:37 2017 thread start!
0
1
3
6
10
15
Sun May 28 21:15:43 2017 thread end!

其中:

lock=threading.Lock()加载锁的方法也可以换成lock=threading.RLock()

如果将上面的sum_num修改为:

  lock.acquire()
  global num
  lock.acquire()
  time.sleep(1)
  num +=i
  lock.release()
  print num
  lock.release()

那么:

lock=threading.Lock() 加载的锁,则一直处于等待中,锁等待

而lock=threading.RLock() 运行正常

以上这篇对python多线程中Lock()与RLock()锁详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python使用xslt提取网页数据的方法

python使用xslt提取网页数据的方法

1、引言 在Python网络爬虫内容提取器一文我们详细讲解了核心部件:可插拔的内容提取器类gsExtractor。本文记录了确定gsExtractor的技术路线过程中所做的编程实验。这是...

python实现从wind导入数据

从wind导入到的数据的格式是instance。 如下载一系列资产在某一段时间的收盘价格。 一系列资产保存在list里面,一并下载。 日期格式为“2018-02-28”。 一个数字串儿表...

Python中staticmethod和classmethod的作用与区别

一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法。 而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用。 这有利于组织...

Centos5.x下升级python到python2.7版本教程

首先到官网下载python2.7.3版本,编译安装 复制代码 代码如下: $wget http://www.python.org/ftp/python/2.7.3/Python-2.7....

python实现比较文件内容异同

本文实例为大家分享了python实现比较文件内容异同的具体代码,供大家参考,具体内容如下 import sys import difflib import time import o...