# -*- coding: utf-8 -*-
# @Author: Li Qin
# @Date:   2020-04-17 11:14:23
# @Last Modified by:   Li Qin
# @Last Modified time: 2020-04-17 11:19:59
# 10.4.13 Synchronizing Operations

import multiprocessing
import time

def stage_1(cond):
    name = multiprocessing.current_process().name
    print(f'Starting {name}')
    with cond:
        print(f'{name} done and ready for stage 2')
        cond.notify_all()

def stage_2(cond):
    name = multiprocessing.current_process().name
    print(f'Starting {name}')
    with cond:
        cond.wait()
        print(f'{name} running')

if __name__ == '__main__':
    condition = multiprocessing.Condition()
    s1 = multiprocessing.Process(name='s1',
                                 target=stage_1,
                                 args=(condition,))
    s2_clients = [
    multiprocessing.Process(
        name=f'stage_2[{i}]',
        target=stage_2,
        args=(condition,),
        )
        for i in range(1, 3)
    ]

    for c in s2_clients:
        c.start()
        time.sleep(1)
    s1.start()

    s1.join()
    for c in s2_clients:
        c.join()