1

I have been trying to pass data into a loop in another process by creating an empty object in which I put the data in. When I change the content of my object the process doesn't seem to update, and keeps returning the same value.

Here is some code I have tried:

from multiprocessing import Process
from time import sleep
class Carrier(): # Empty object to exchange data
 pass
def test():
 global carry
 while True:
 print(carry.content)
 sleep(0.5)
carry = Carrier()
carry.content = "test" # Giving the value I want to share
p = Process(target=test, args=())
p.start()
while True:
 carrier.content = input() # Change the value from the object

I have also tried deleting the object from memory each time and redefining it in the next loop but doesn't seem to have any effect, instead it keeps the initial "test" value, the one present when it was executed.

asked Mar 6, 2019 at 10:13
4
  • The carry variable is defined after def test(). The global carry statement cannot find a carry variable at the time when def test() is being defined. Commented Mar 6, 2019 at 10:20
  • The order doesn't have an effect, the function is called after its defined, and in the first loop one can see carry was defined as it prints the initial value of "test". Commented Mar 6, 2019 at 10:24
  • You can't share variables in Process like that. Commented Mar 6, 2019 at 10:27
  • Hi, this is because you are starting different process and in python each process gets its own property of global variables. hence each of your process will get the carry.content as test. Also in multiprocessing in python make sure to update global variables inside the callbacks function so that each process gets the same set of global variables. Commented Mar 6, 2019 at 10:47

1 Answer 1

0

I assuming that you are running this program on windows as the child process or threads you open in a program are independent of their parent process. So you actually can't share data between the process like this.

It is possible to share data in when running python on linux as the spawned processes are child of parent process where it can share the data.

To be able to share data between parent and child process irrespective of the underlying OS, you can see this link - How to share data between Python processes?

answered Mar 6, 2019 at 10:25
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.