2

here is my code

from multiprocessing import Pool
a = []
def f(x):
    a.append(x*x)
    return x*x

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))


print(a)

I would expect print(a) to output [1,4,9]. However, it just outputs an empty array. Is there a way to easily fix this, ideally allowing f() to access a?

Hirusha Fernando
  • 1,156
  • 10
  • 29
Dylan Ong
  • 786
  • 2
  • 6
  • 14
  • 2
    Multiple processes *do not share state* because they are *seperate python processes*. There are various approaches to sharing state, none of which are straight forward. Ideally, multiprocessing code should be designed to not need it, but [check out the docs for some options](https://docs.python.org/3/library/multiprocessing.html#sharing-state-between-processes) – juanpa.arrivillaga Jan 16 '21 at 04:50
  • The `print` of `p.map` has the answer anyway. Just delete `a = []`, `a.append(x*x)`, and `print(a)`. `Pool` collects the results. – Mark Tolonen Jan 16 '21 at 07:41

0 Answers0