0

it seems I just cant wrap my head around how this works, I know it might be a stupid question, but I didnt understand how to do that even tho I looked after similar questions, in essence I just want the processes to use the same variable and change its value on the fly, output I am getting is

carl
10
bob
10

when it should be

carl
10
bob
5
from multiprocessing import Process, Manager, Value
import os
import time

xVal = Value('i', 0)
xVal.value = 10

def subtract(x):
  xVal.value -= x

def name1(title):
  time.sleep(5)
  x = xVal.value
  print(title)
  print(x)
  subtract(5)

def name2(name):
  time.sleep(10)
  x = xVal.value
  print(name)
  print(x)

if __name__ == '__main__':
    #info('main line')
    d = Process(target=name1, args=('carl',))
    p = Process(target=name2, args=('bob',))
    d.start()
    p.start()
  • there's more to having shared variables when using multiprocessing. ( issues related to race conditions, etc ) see: https://stackoverflow.com/questions/10415028/how-can-i-recover-the-return-value-of-a-function-passed-to-multiprocessing-proce and https://stackoverflow.com/questions/17377426/shared-variable-in-pythons-multiprocessing and https://stackoverflow.com/questions/1312259/what-is-the-re-entrant-lock-and-concept-in-general – jmunsch Jun 29 '20 at 20:33
  • Please provide a minimal reproducible code. – Red Jun 29 '20 at 20:42
  • 1
    sorry, forgot a import :p @AnnZen – Marcelo Aguiar Jun 29 '20 at 20:59
  • I'm not getting `carl 10 bob 10`... – Red Jun 29 '20 at 21:01
  • I made the output more clear through a edit, is yours different than that? – Marcelo Aguiar Jun 29 '20 at 21:08
  • I get Carl 10, Bob 10 too. It's been a while since I messed with multiprocesses, but I see what you are trying to do. I suspect what the problem is. Let me check my archives to be sure and I will post the answer if my suspicions are verified. – user10637953 Jun 29 '20 at 21:17
  • I didn't get any output. note that since you did not add @AnnZen to your comment, I never got a notification in my inbox. – Red Jun 29 '20 at 21:17
  • This is an interesting little puzzle. My suspicion, that the sleep command was to blame, was incorrect. Even when I use a timer rather than Sleep, I still get Carl 10, Bob 10. Let me mess with it a bit and see if I can get it to work as intended. (My archive files were no help as I have never tried to get two different processes to access the same variable.) If I can get them to play nice, I will post it. In the mean time, maybe someone else can explain what is going on. – user10637953 Jun 29 '20 at 21:36
  • I have to tap out. After reading jmunsh's links, it's clear that I am over my head on this topic. It is a branch of multiprocessing that I have not studied. Sorry. – user10637953 Jun 29 '20 at 21:46

0 Answers0