I wanted to have a shared counter in multiprocessing.Pool
and I use the following code to print the varying input list:
import multiprocessing
running = multiprocessing.Value('i', 0)
def f(x):
global running
global lock
# ... code ...
with lock:
running.value -= 1
print(f"Still running: {running.value}\n", end='', flush=True)
return x
if __name__ == '__main__':
lock = multiprocessing.Lock()
rangeval = range(100)
running.value = len(rangeval)
pool = multiprocessing.Pool(processes=multiprocessing.cpu_count())
result = pool.map(f, iterable=rangeval)
This works well in Mac and Linux. But when I run it in Windows it produces an error:
File "C:\...\...\...\...\main.py", line 11, in f
with lock:
NameError: name 'lock' is not defined
When I put lock = multiprocessing.Lock()
outside the if __name__ == '__main__'
on top of the function f
, it produces a weird output like the following:
Still running: -1
Still running: -2
Still running: -3
Still running: -4
Still running: -1
Still running: -2
Still running: -3
Still running: -4
How can this be solved in Windows?