I would like to run two functions at the same time. One of the functions has to access the created variables of the other one.
What I’ve done so far:
import multiprocessing import Process import sys import time def func1(): x = 0 while True: x += 1 time.sleep(1) return x def func2(): y = 0 while True: y = x print(y) time.sleep(1) return y if __name__=='__main__': p1 = Process(target = func1()) p1.start() p2 = Process(target = func2()) p2.start() p1.join() p2.join()
The functions will be executed both but the x wont’t be recognised in the second function and instead is is just printed y = 0.
How can I use the current value of my variable x in function 2?
In my case I have to use a gps hat of my raspberry pi which needs a couple of seconds to be read. Independendly of my this gps function I would like to run function2 and while executing it, I take the current gps data every loop.
Processes don’t share globals. Have a look at this: Exchanging objects between processes
Variables declared in a function are only accessible within that function and cease to exist afterwards.
If you want to share a variable declare it in module scope and mark it global in each function you want to use it within.
shared = 0 def func_1(): global shared shared = shared + 1 print ("func_1 shared=", shared) def func_2(): global shared shared = shared + 51 print ("func_2 shared=", shared)
It is your responsibility to ensure overlapping changes to the global are safe.