Python的Lock和condition使用
Lock是threading模块提供的锁对象,Lock默认创建的是一个锁对象,当我们需要对全局对象进行操作的时候,可以通过Lock创建对象来锁定对象,Lock对象就好比java中的synchronize(aObject)代码中的aObject对象。
而condition除了具有Lock对象的acquire方法和release方法外,还有wait、notify、notifyAll方法等用于条件处理。Condition对象可以在某些事件触发或者达到特定条件后才处理数据。很像java中锁一个对象后,对象调用notify或者notifyAll方法去触发操作。Condition还支持从外界引用一个Lock对象。
Lock示例代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time import threading class MyThread(threading.Thread):
def run(self):
global counter
time.sleep(1)
# 获得锁对象
if mutex.acquire(1):
counter = counter + 1
msg = self.name + ' set counter to '
+ str(counter)
print msg
#释放锁
mutex.release() # 全局变量 counter = 0 #产生一个互斥锁 mutex = threading.Lock() def test():
for i in
range(0,
5):
t = MyThread()
t.start() if __name__ == '__main__':
test()
|
输出内容:
Thread-1 set counter to 1
Thread-3 set counter to 2
Thread-2 set counter to 3
Thread-4 set counter to 4
Thread-5 set counter to 5
|
Condition代码示例:
#!/usr/bin/env Python
# -*- coding: utf-8 -*- import threading,
time class Seeker(threading.Thread):
def __init__(self,
cond, name):
super(Seeker,
self).__init__()
self.cond = cond
self.name = name
def run(self):
self.cond.acquire()
print self.name +
': 我已经把眼睛蒙上了'
"""
notify源码解析:
__waiters = self.__waiters
waiters = __waiters[:n] # 获取等待队列中的n个等待锁
for waiter in waiters:
waiter.release() # 释放Hider的等待锁
try:
__waiters.remove(waiter)
except ValueError:
pass
"""
# 释放n个waiter锁,waiter线程准备执行
self.cond.notify()
print('notifyed...')
# 释放condition条件锁,waiter线程Hider真正开始执行
self.cond.wait()
print('waited...')
print self.name +
': 我找到你了 ~_~'
self.cond.notify()
self.cond.release()
print self.name +
': 我赢了'
class Hider(threading.Thread):
def __init__(self,
cond, name):
super(Hider,
self).__init__()
self.cond = cond
self.name = name
def run(self):
self.cond.acquire()
"""
wait()源码解析:
waiter = _allocate_lock() # 创建一把等待锁,加入waiters队列,等待notify唤醒
waiter.acquire() # 获取锁
self.__waiters.append(waiter)
saved_state = self._release_save() # 释放condition.lock全局条件锁,以便其他等待线程执行
if timeout is None:
waiter.acquire() # 再次获取锁,因为已经锁定无法继续,等待notify执行release
"""
# wait()释放对琐的占用,同时线程挂起在这里,直到被notify并重新占有琐。
self.cond.wait()
print self.name +
': 我已经藏好了,你快来找我吧'
self.cond.notify()
self.cond.wait()
self.cond.release()
print self.name +
': 被你找到了,哎~~~' cond = threading.Condition()
hider = Hider(cond, 'hider')
seeker = Seeker(cond, 'seeker')
hider.start()
seeker.start()
hider.join()
seeker.join() print('end...')
|
输出结果:
seeker: 我已经把眼睛蒙上了
notifyed...
hider: 我已经藏好了,你快来找我吧
waited...
seeker: 我找到你了 ~_~
seeker: 我赢了
hider: 被你找到了,哎~~~
end...
|
Python的Lock和condition使用
0