2

I want to use multiprocessing for my project at school but I have a problem with shared variables between multiple processes. To simulate the problem, I made some code to show you:

import multiprocessing
import ctypes
import time


def function1():
    global value

    while True:
        value.value += 1
        time.sleep(1)


def function2():
    global value

    while True:
        value.value += 1
        time.sleep(1)


if __name__ == "__main__":
    manager = multiprocessing.Manager()
    value = manager.Value("i", 0)

    process1 = multiprocessing.Process(target=function1)
    process2 = multiprocessing.Process(target=function2)
    process1.start()
    process2.start()

    while True:
        print(value.value)
        time.sleep(1)

this is the error message that I get:

NameError: name 'value' is not defined

Can someone help me with this please? Thank you

samsepi
  • 41
  • 4

1 Answers1

3

You need to pass the shared memory value to each function, they are not able to access the value with global.

import multiprocessing
import ctypes
import time


def function1(value):
    while True:
        value.value += 1
        time.sleep(1)


def function2(value):
    while True:
        value.value += 1
        time.sleep(1)


if __name__ == "__main__":
    manager = multiprocessing.Manager()
    value = manager.Value("i", 0)

    process1 = multiprocessing.Process(target=function1, args=(value,))
    process2 = multiprocessing.Process(target=function2, args=(value,))
    process1.start()
    process2.start()

    while True:
        print(value.value)

Stepan
  • 504
  • 5
  • 12
  • Thank you for your fast response! I edited the original post – samsepi Jan 14 '21 at 16:03
  • Sorry, but I do not understand your edits. What does it mean " I use an input to start the game"? which " two variables should change"? How these two boxes of code relates to each other? From my point of view, the edits you made are more like a new question, probably you should consider of asking a new questions, after proper question formulation. – Stepan Jan 14 '21 at 16:13
  • I'm new here sorry, the input is pressing on enter, I will open a new question, thank you – samsepi Jan 14 '21 at 16:21
  • Welcome and enjoy) – Stepan Jan 14 '21 at 16:25