I'm using multiprocessing to create a sub-process to my Python app. I would like to share data between my parent process and the child process. it's important to mention that I need to share this asynchronously, means that the child process and the parent process will update the data during the code running.
What would be the best way to perform that?
To share big data: named shared-memory The fastest way to handle this is to create a file mapping object, map the file object into memory space, notify the parent process of the file mapping handle and data size, and then dump the data to the mapped buffer for the parent process to read.
Every object has two methods – send() and recv(), to communicate between processes.
00:11 By default, each of your processes is given a private chunk of memory for its own use by the operating system. If you want to share memory between processes, you can make a call to the OS to get this done. 00:24 mmap is one of the ways to do this.
multiprocessing is a drop in replacement for Python's multiprocessing module. It supports the exact same operations, but extends it, so that all tensors sent through a multiprocessing. Queue , will have their data moved into shared memory and will only send a handle to another process.
Here's an example of multiprocess-multithread and sharing a couple variables:
from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread
ps = []
def yourFunc(pause, budget):
while True:
print(budget.value, pause.value)
##set value
pause.value = True
....
def multiProcess(threads, pause, budget):
for _ in range(threads):
t = Thread(target=yourFunc(), args=(pause, budget,))
t.start()
ts.append(t)
time.sleep(3)
if __name__ == '__main__':
pause = Value(c_bool, False)
budget = Value('i', 5000)
for i in range(2):
p = Process(target=multiProcess, args=(2, pause, budget))
p.start()
ps.append(p)
This is one simple example from python documentation -
from multiprocessing import Process, Queue
def f(q):
q.put([42, None, 'hello'])
if __name__ == '__main__':
q = Queue()
p = Process(target=f, args=(q,))
p.start()
print q.get() # prints "[42, None, 'hello']"
p.join()
You can use pipe as well, Refer for more details - https://docs.python.org/2/library/multiprocessing.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With