1. 程式人生 > >Python多程序,同步互斥,訊號量,鎖補充上一篇文章

Python多程序,同步互斥,訊號量,鎖補充上一篇文章

from multiprocessing import Event,Process
from time import sleep

def wait_event1():
    print("1想操作臨界區資源")
    e.wait()
    print("1開始操作臨界區資源",e.is_set())
    with open("file") as f:
        print(f.read())
def wait_event2():
    print("2也想操作臨界區資源")
    # 超時3秒檢測
    e.wait(3)
    # 判斷是否被設定
    if e.is_set():
        
print("2開始操作臨界區資源",e.is_set()) with open("file") as f: print(f.read()) else: print("2不能操作") # 建立事件物件 e = Event() p1 = Process(target = wait_event1) p2 = Process(target = wait_event2) p1.start() p2.start() print("主程序操作") with open("file",'w') as f: f.write(
"HELLO WORD") # 延遲4秒釋放臨界區 sleep(4) # 釋放臨界區資源 e.set() print("釋放臨界區") p1.join() p2.join()