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

0

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your fast response! I edited the original post
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.
I'm new here sorry, the input is pressing on enter, I will open a new question, thank you
Welcome and enjoy)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.