Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share data between Python processes?

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?

like image 891
Dan Avatar asked Feb 02 '16 15:02

Dan


People also ask

How do I share data between processes?

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.

How do you communicate two processes in Python?

Every object has two methods – send() and recv(), to communicate between processes.

Do Python processes share memory?

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.

Does Python multiprocessing use shared memory?

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.


2 Answers

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) 
like image 135
grantr Avatar answered Oct 21 '22 13:10

grantr


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

like image 23
AlokThakur Avatar answered Oct 21 '22 13:10

AlokThakur