python process synchronization-Event

Event actually describes a kind of synchronous processing time, which can be simply understood as that between different processes, some special processing can be used to wait for the completion of other processes;
personally, this is equivalent to providing a blocking method For example, if you open two processes to operate at the same time, but one of your processes depends on the other process to complete the operation, then use Event at this time; the
code example is as follows, but it needs to be blocked and unblocked frequently, it seems very Is trouble;

import multiprocessing, time


def restaurant_handle(event):
    print("1.【餐厅】为食客安排座位,并在一旁等待食客点餐...");
    # 餐厅在等食客点餐,模拟实际点餐操作的逻辑耗时
    time.sleep(1);
    # 解除阻塞状态
    event.set();
    # 清楚已有的状态
    event.clear();
    # 等待食客后续处理
    event.wait();
    # 当进行了第二部的时候执行第三部,进行做饭
    print("3.【餐厅】厨师开始做饭啦...");
    # 饭做好了,解除食客等待
    event.set();
    # 清楚已有的状态
    event.clear();
    pass;


def diners_handle(event):
    # 等待上面餐厅第一步完成之后才可以执行
    event.wait();
    print("2.【食客】看完菜单,选好了吃的...");
    # 食客下单之后这里餐厅需要进行做饭,模拟实际做饭的耗时
    time.sleep(1);
    event.set();
    # 清楚已有的状态
    event.clear();
    # 等饭做好可以吃;
    event.wait();
    print("4.【食客】开始吃饭了...");
    pass;

def main():
    event = multiprocessing.Event();
    restaurant_process = multiprocessing.Process(target=restaurant_handle,args=(event,),name="餐厅服务进程");
    diners_process = multiprocessing.Process(target=diners_handle,args=(event,),name="食客服务进程");
    restaurant_process.start();
    diners_process.start();

if __name__ == '__main__':
    main();

Guess you like

Origin blog.csdn.net/weixin_44887276/article/details/114867376