标准库模块multiprocessing(七)--Event事件--同步机制
from multiprocessing import Event
1、创建事件对象
e = Event()
2、事件阻塞
e.wait([timeout])
功能 : 使进程处于阻塞状态,直到事件对象被set
3、事件设置
e.set()
功能 : 让事件对象变为被设置状态
4、清除设置
e.clear()
功能 : 使事件对象清除设置状态
5、事件判断
e.is_set()
功能:判断当前事件对象的状态
from multiprocessing import Event
#创建对象
e = Event()
e.set() #设置事件
e.wait(5)
print("========================")
print(e.is_set())
e.clear() #清除设置状态
e.wait()
from multiprocessing import Process,Event
from time import sleep
def wait_event(file):
print("准备操作临界资源")
e.wait()
print("开始操作临界资源",e.is_set())
fw = open('1.jpg','wb')
with open(file,'rb') as f:
fw.write(f.read())
def wait_event_timeout(file):
print("也想操作临界资源")
e.wait(2)
if e.is_set():
print("也开始操作临界资源")
fw = open('2.jpg','wb')
with open(file,'rb') as f:
fw.write(f.read())
else:
print("等不了了,不等了")
e = Event()
path = "/home/tarena/file.jpg"
file = 'file.jpg'
p1 = Process(target = wait_event,args = (file,))
p2 = Process(target = wait_event_timeout,args = (file,))
p1.start()
p2.start()
print("主进程在操作临界资源")
sleep(3)
fw = open(file,'wb')
with open(path,'rb') as f:
fw.write(f.read())
fw.close()
e.set()
print("主进程操作完毕")
p1.join()
p2.join()