python mutiprocessing on windows using shared values

57 Views Asked by At

I am trying to gain an insight into using multiprocessing with python. I have an example of using shared values for Unix but I cannot get a simple educational example to work on Windows 10. I have the code below running ok on Windows but with the call updating the shared value commented out in foo(). What is my problem please?

import multiprocessing as mp

def foo(q):
    #global shared_num
    q.put('hello')
    #shared_num.value = 777

if __name__ == '__main__':
    global shared_num
    mp.set_start_method('spawn')
    shared_num = mp.Value('d', 0)
    lock = mp.Lock()
    q = mp.Queue()
    p = mp.Process(target=foo, args=(q,))
    p.start()
    p.join()
    print(q.get(), " ",shared_num.value)
    #print(q.get(), " ")

If I run the code below with the foo() setting the shared value I get:

Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2032.0_x64__qbz5n2kfra8p0\lib\multiprocessing\process.py", line 315, in _bootstrap
    self.run()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2032.0_x64__qbz5n2kfra8p0\lib\multiprocessing\process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\ken38\OneDrive\Projects\Python\GH_Pi\python\ms_mp.py", line 6, in foo
    shared_num.value = 777
NameError: name 'shared_num' is not defined
hello   0.0
1

There are 1 best solutions below

0
On

Michael Butscher actually answered this with his comment. But as I could not flag that as an answer I thought I would show the corrected code as an answer. This does highlight difference if you try and test simple examples on Windows. Linux based examples may not work an Windows. This code worked on both Windows and Debian (Rpi).

import multiprocessing as mp

def foo(q, shared_num, lock):
    #global shared_num
    q.put('hello')
    with lock:
        shared_num.value = 777

if __name__ == '__main__':
    global shared_num
    mp.set_start_method('spawn')
    shared_num = mp.Value('d', 0)
    lock = mp.Lock()
    q = mp.Queue()
    p = mp.Process(target=foo, args=(q, shared_num, lock,))
    p.start()
    p.join()
    print(q.get(), " ",shared_num.value)
    #print(q.get(), " ")