Relationship between parent and child process when forcing in Python

I tried to have the Python program run the processing loop and the broadcast service for the result at the same time using the os.fork () call, something like

pid = os.fork()
if pid == 0:
    time.sleep(3)
    keep_updating_some_value_while_parent_is_running()
else:
    broadcast_value()

Here keep_updating_some_value_while_parent_is_running(), which is executed by the child, stores some value that it continues to update while the parent is running. It actually writes the value to disk so that the parent can easily access it. He discovers that the parent is working, checking that the web service that he is starting is available.

broadcast_value() starts a web service, when accessing it reads the latest value from the disk and serves it.

This implementation works well, but it is unsatisfactory for several reasons:

  • time.sleep(3) , - . , 3 , .

  • ( ).

  • , , , - , , , , ( ), . , , - , .

  • .

  • - , ( , ).

, - , , , , , . , .

+4
1

multiprocessing, os.fork(), . , Manager, . Process , - , Manager. ( ), Manager).

:

import time
from multiprocessing import Manager, Process

def get_data():
    """ Does the actual work of getting the updating value. """

def update_the_data(shared_dict):
    while not shared_dict.get('server_started'):
        time.sleep(.1)
    while True:
        shared_dict['data'] = get_data()
        shared_dict['data_timestamp'] = time.time()
        time.sleep(LOOP_DELAY)


def serve_the_data(shared_dict):
    server = initialize_server() # whatever this looks like
    shared_dict['server_started'] = True
    while True:
        server.serve_with_timeout()
        if time.time() - shared_dict['data_timestamp'] > 30:
            # child hasn't updated data for 30 seconds; problem?
            handle_child_problem()


if __name__ == '__main__':
    manager = Manager()
    shared_dict = manager.dict()
    processes = [Process(target=update_the_data, args=(shared_dict,)),
        Process(target=serve_the_data, args=(shared_dict,))]
    for process in processes:
        process.start()
    for process in processes:
        process.join()
+2

Source: https://habr.com/ru/post/1693332/


All Articles