码迷,mamicode.com
首页 > 其他好文 > 详细

Lock()与RLock()锁

时间:2018-12-17 11:36:36      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:def   global   cti   glob   keyboard   输出   方法   print   rgs   

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

锁提供如下方法:
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
1
2
3
4
5
6
结果显示混乱

引入锁:

#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() 运行正常

Lock()与RLock()锁

标签:def   global   cti   glob   keyboard   输出   方法   print   rgs   

原文地址:https://www.cnblogs.com/yoyo1216/p/10129761.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!