I'm trying to create an array of functions that I then execute in Parallel. I found this answer on SO, and so have a POC script like this:
from multiprocessing import Process
def runInParallel(*fns):
processes = []
for fn in fns:
p = Process(target=fn)
p.start()
processes.append(p)
for p in processes:
p.join()
fns = []
def hi(x):
print(x) # This always prints out '5'
for i in range(6):
fns.append(lambda: hi(i))
runInParallel( *fns)
My intention is that the body of the lambda function would be closure over the value of the i
variable at the time of lambda definition. But this is not occurring. Instead when I execute the functions all the i
values are '5'.
How can I create closure over a variable in a for loop?