Home > Backend Development > Python Tutorial > How do I update global variables from child processes in multiprocessing and ensure they are accessible by the parent process?

How do I update global variables from child processes in multiprocessing and ensure they are accessible by the parent process?

Susan Sarandon
Release: 2024-11-06 15:08:02
Original
403 people have browsed it

How do I update global variables from child processes in multiprocessing and ensure they are accessible by the parent process?

Multiprocessing Global Variable Updates Not Returned to Parent

When utilizing multiprocessing to establish a secondary process, a distinct Python instance is created with its own global state. This global state is isolated, rendering any modifications made to global variables by child processes invisible to the parent process.

Moreover, the majority of multiprocessing abstractions leverage pickle to transfer data. All data conveyed via proxies must be pickleable, including all objects provided by a Manager. The Manager section emphasizes that other processes can access shared objects using proxies.

Similar restrictions apply to Queues, though the documentation omits this information. A quick test confirms that all data in Queues must also be pickleable.

If pickling your data remains infeasible, consider storing it as a ctype object and passing a memory reference to a child process. This approach is somewhat risky and should be reserved for situations where other options are exhausted.

In your case, understanding the complexities of LORR is crucial. If it's a Python class, subclassing from it and defining setstate and getstate methods may facilitate pickling.

Alternatively, extracting the required data from a LORR instance and passing it through a simple string may suffice. Consider utilizing Queues to send messages between the main process and child processes to invoke object methods directly, as illustrated in the schematic above.

The above is the detailed content of How do I update global variables from child processes in multiprocessing and ensure they are accessible by the parent process?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template