Hey! This is Mort!

I'm software engineer and open source enthusiast especially in C/C++ & Python and GNU/Linux.
Home Resume Github LinkedIn Twitter m@0t1.me

Python Shared Data Between Processes 2017 Nov 11

Providing a shared data or state between different processes is so useful and great idea because in many cases when you want to implement parallel systems, you should provide a way that each process can communicate with others.

Fortunately, Python supports many kinds of shared data such as Value, Array, Dict, and Queue and so on.

Let’s try an example:

We have 2 processes which are:

from multiprocessing import Process, Value
from ctypes import c_char
from time import sleep

def process_1(shared_data):
    """Process-1 is responsible to check the value."""
    while shared_data.value != b"my_data":
    print("process-1 got the value. exit.")

def process_2(shared_data):
    """Process-2 is responsible to set value."""
    shared_data.value = b"my_data"
    print("process-2 set the value. exit.")

if __name__ == "__main__":
    # create a shared data with 10 character length
    shared_data = Value(c_char * 10)
    p1 = Process(target=process_1, args=(shared_data,))
    p2 = Process(target=process_2, args=(shared_data,))

Try to implement your projects and idea with this great features which help you to have high performance and scalable systems.


All rights reserved by Morteza NourelahiAlamdari ©
All contents are under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.