0

I'm trying to set a global variable in one process and read it from another process. This is basically what i am doing:

from multiprocessing import Process
import time

rocket = 0

def func1():
    global rocket
    while rocket < 10:
        rocket += 1
        print("Func1: " + str(rocket))
        time.sleep(5)

def func2():
    while rocket < 10:
        print ("Func2: " + str(rocket))
        time.sleep(1)

if __name__=='__main__':
     p1 = Process(target = func1)
     p1.start()
     p2 = Process(target = func2)
     p2.start()

What I think this code should be doing:

  • func1 increases the global variable 'rockets' by 1 every five seconds
  • Every second func2 reads the global variable rockets and prints it
  • The two methods run parralel until 'rockets' == 10

So the expected output should be something like:

Func1: 1
Func2: 1
Func2: 1
Func2: 1
Func2: 1
Func2: 1
Func1: 2
Func2: 2
Func2: 2
#... and so on

But the actual output goes like:

Func1: 1
Func2: 0
Func2: 0
Func2: 0
Func2: 0
Func2: 0
Func1: 2
Func2: 0
Func2: 0
#... and so on

When printed from func2 'rockets' always stays 0

I am declaring 'rockets' as a global variable in func1 as you should

What am I missing here?

Tobi o' Bobi
  • 197
  • 9
  • Possible duplicate of [Python multiprocessing global variable updates not returned to parent](https://stackoverflow.com/questions/11055303/python-multiprocessing-global-variable-updates-not-returned-to-parent) – cbolles Jul 18 '17 at 15:42

2 Answers2

0

You could try and set global rocket = 0 and delete the line rocket = 0

aatate98
  • 11
  • 5
0

I finally got it!

You can't use global variables the way I intended.

Instead you use a Queue to exchange data between processes.

The docu has an example on this.

So you can do something like this:

from multiprocessing import Process, Queue
import time

def func1(q):
    q.put("FirstValue")
    time.sleep(10)
    q.put("SecondValue")


def func2(q):
    time.sleep(5)
    print ("Func2: " + str(q.get()))
    time.sleep(15)
    print ("Func2: " + str(q.get()))


if __name__=='__main__':
    q = Queue()

    p1 = Process(target = func1, args=(q,))
    p1.start()
    p2 = Process(target = func2, args=(q,))
    p2.start()

Which prints:

Func2: FirstValue
Func2: SecondValue
Tobi o' Bobi
  • 197
  • 9