Sobes.tech
Junior — Middle

Is it possible to share a variable between multiple processes in Python and how to implement it?

sobes.tech AI

Answer from AI

In Python, you can share data between processes using the multiprocessing module, which provides special objects for shared access to variables.

Main methods:

  • multiprocessing.Value — for sharing a single value (e.g., a number).
  • multiprocessing.Array — for sharing an array of data.
  • multiprocessing.Manager — creates a server that allows creating shared objects (lists, dictionaries, etc.) accessible from different processes.

Example with Value:

from multiprocessing import Process, Value

def worker(num):
    num.value += 1

if __name__ == '__main__':
    shared_num = Value('i', 0)  # 'i' — integer type
    processes = [Process(target=worker, args=(shared_num,)) for _ in range(5)]
    for p in processes:
        p.start()
    for p in processes:
        p.join()
    print(shared_num.value)  # Will output 5

Thus, the variable shared_num is shared among processes and can be modified by them.