0

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?

Zach Smith
  • 8,458
  • 13
  • 59
  • 133
  • 1
    Consider using `functools.partial`: `[functools.partial(hi, i) for i in range(6)]` – Mechanic Pig Jun 19 '22 at 07:36
  • 1
    Although, since your function is always the same and only the argument changes, you may want to use a multiprocessing Pool and `.map()` instead, since then you can pass a list of function arguments that will be iterated over. – 9769953 Jun 19 '22 at 07:36
  • 3
    Does https://stackoverflow.com/questions/3431676/creating-functions-in-a-loop answer your question? – Thierry Lathuille Jun 19 '22 at 07:36
  • So, see the [accepted answer here](https://stackoverflow.com/a/2295368/5014455) – juanpa.arrivillaga Jun 19 '22 at 07:52

0 Answers0