当前位置:首页 >> 脚本专栏

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

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

也可能导致读写混乱

锁提供如下方法:

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()锁详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。