Reputation: 11
When using the .start()
method to execute a function, the function doesn't work as I expected. I can see that the line time.sleep()
works, but changing the variable and print statement does. The functions executes when the .run()
method is called, but this runs the code in series to other functions and not multiprocessing.
from multiprocessing import Process
import time
import sys
worker1 = None
worker2 = None
def worker():
time.sleep(60)
worker1 = 6
print("hello")
sys.stdout.flush()
def workertwo():
time.sleep(60)
worker2 = 6
print("world")
sys.stdout.flush()
if __name__ == '__main__':
hello = Process(target=worker)
world = Process(target=workertwo)
world.start()
hello.start()
world.join()
hello.join()
print(worker1)
print(worker2)
This is just a test piece of code that shares the problem with a larger software. I'm running on a windows 10 machine, running python 3.6.8
when I run this code I get:
None
None
>>>
but I would expect to get:
hello
world
6
6
>>>
Its being ran from a script file but does work when being ran from inside the command prompt. It will be running alongside a tkinter GUI so would need to run from the script (I assume)
This is my first question on here, and I'm self-taught. Any guidance would be helpful,
thanks Danny
Upvotes: 1
Views: 507
Reputation: 2406
You're trying to share a global variable between multiple processes which obviously doesn't work. Possible options for sharing variables in memory between processes are described here: https://docs.python.org/3/library/multiprocessing.html#sharing-state-between-processes
from multiprocessing import Process, Value
import time
import sys
worker1 = Value('i', 0)
worker2 = Value('i', 0)
def worker(worker1):
time.sleep(3)
worker1.value = 6
print("hello")
sys.stdout.flush()
def workertwo(worker2):
time.sleep(3)
worker2.value = 6
print("world")
sys.stdout.flush()
if __name__ == '__main__':
hello = Process(target=worker, args=(worker1,))
world = Process(target=workertwo, args=(worker2,))
world.start()
hello.start()
world.join()
hello.join()
print(worker1.value)
print(worker2.value)
OUT:
world
hello
6
6
Upvotes: 1