Python process synchronization-Barrier

Barrier represents a kind of barrier. When several processes do not reach the number of barriers, they are in a blocked state. Once the number of barriers is reached, the blocking state will be automatically unblocked and run; the
above description may be more difficult to understand, we can simply It is understood that when the process is executing synchronously, if there are a total of 3 processes at this time, two of them have executed a certain logic and need to proceed to the next step, and the third has not executed the corresponding logic, then the first two will be in The blocked state is not executed. After the third is executed, the three will proceed to the next logical processing together;

Code example

import multiprocessing, time

# 需要后续执行的方法
def barier_handle():
    print("三个进程执行完毕了,开始执行后续的流程");

def arrangement(barrier):
    print("第:{}个开始准备执行".format(multiprocessing.current_process().name));
    # 模拟实际的业务逻辑的处理时间;
    time.sleep(2);
    # 进入屏障点等待 (达到三个执行的进程);
    barrier.wait();
    print("第:{}个准备完毕,和其他两个一起开始下一步".format(multiprocessing.current_process().name));

def main():
    # 每达到三个进程的时候调用后续处理函数
    barrier = multiprocessing.Barrier(parties=3,action=barier_handle);
    process_list = [multiprocessing.Process(target=arrangement,args=(barrier,),name="奥特曼:{}号".format(item)) for item in range(12)];
    for process in process_list:
        process.start();
    for process in process_list:
        process.join();
    # 结束同步
    barrier.abort();
if __name__ == '__main__':
    main();

Guess you like

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