Problem
I'm using Python's multiprocessing module to execute functions asynchronously. What I want to do is be able to track the overall progress of my script as each process calls and executes def add_print
. For instance, I would like the code below to add 1 to total
and print out the value (1 2 3 ... 18 19 20
) every time a process runs that function. My first attempt was to use a global variable but this didn't work. Since the function is being called asynchronously, each process reads total
as 0 to start off, and adds 1 independently of other processes. So the output is 20 1
's instead of incrementing values.
How could I go about referencing the same block of memory from my mapped function in a synchronous manner, even though the function is being run asynchronously? One idea I had was to somehow cache total
in memory and then reference that exact block of memory when I add to total
. Is this a possible and fundamentally sound approach in python?
Please let me know if you need anymore info or if I didn't explain something well enough.
Thanks!
Code
#!/usr/bin/python
## Import builtins
from multiprocessing import Pool
total = 0
def add_print(num):
global total
total += 1
print total
if __name__ == "__main__":
nums = range(20)
pool = Pool(processes=20)
pool.map(add_print, nums)