嘿嘿,有的时候两个人一起干活还是需要交流的,就算是博主一值都拿生产饼干的例子来作为说明的材料,上一篇文章使用信号量表示控制同时干活的进程的数量,现在需要两个人干活的时候需要多交流交流,这个可以通过event实现进程之间的通信
首先我们先看下Event类的定义
class Event(object):
def __init__(self):
self._cond = Condition(Lock())#条件锁
self._flag = Semaphore(0)#信号量参数为0,表示允许操作的进程数为0,初始化可以表明当前进程被阻塞
def is_set(self):
self._cond.acquire()#获取锁
try:
if self._flag.acquire(False):#当前进程不需要占用资源了
self._flag.release()#释放资源
return True
return False
finally:
self._cond.release()#释放锁
def set(self):
self._cond.acquire()
try:
self._flag.acquire(False)
self._flag.release() #释放资源,那么允许其他进程操作资源
self._cond.notify_all()#通知其他所有进程
finally:
self._cond.release() #释放锁资源
def clear(self):
self._cond.acquire()
try:
self._flag.acquire(False)
finally:
self._cond.release()
def wait(self, timeout=None):
self._cond.acquire()
try:
if self._flag.acquire(False):
self._flag.release()
else:
self._cond.wait(timeout)
if self._flag.acquire(False):
self._flag.release()
return True
return False
finally:
self._cond.release()
测试代码
import multiprocessing
import time
def wait_for_event(e):
print("wait_for_event: starting")
e.wait()
print("wairt_for_event: e.is_set()->" + str(e.is_set()))
def wait_for_event_timeout(e, t):
print("wait_for_event_timeout:starting")
e.wait(t)
print("wait_for_event_timeout:e.is_set->" + str(e.is_set()))
if __name__ == "__main__":
e = multiprocessing.Event()
w1 = multiprocessing.Process(name = "block",
target = wait_for_event,
args = (e,))
w2 = multiprocessing.Process(name = "non-block",
target = wait_for_event_timeout,
args = (e, 2))
w1.start()
w2.start()
time.sleep(3)
e.set()
print("main: event is set")
输出
wait_for_event: starting 表示name为block的进程启动,但是执行到wait()函数那被阻塞了
wait_for_event_timeout:starting 表示name为non-block的进程启动,但是执行到wait(2),阻塞两秒继续执行
wait_for_event_timeout:e.is_set->False 由于初始化event对象self._flag = Semaphore(0) 所以is_set函数输出为false
mwain: event is set 主进程设置了e.set()
airt_for_event: e.is_set()->True