0

Using my sample script

from multiprocessing import Pool


def methodUsingPool(x):
    if __name__ == '__main__':
        pool = Pool()
        pool.map(print, x)


methodUsingPool("x")
print("1")

gets the output

1
1
1
1
1
1
x
1

while I've been expecting

x
1

Why is that so? What can I do?

Patrick Rode
  • 120
  • 1
  • 13
  • 1
    Can't replicate the problem with your code. Are you sure it's the only place where it is run? Also you could close or terminate the pool: https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool – haxor789 Feb 24 '22 at 12:03
  • 1
    And in addition to the fine answer by Olvin, you can read more here: https://stackoverflow.com/questions/419163/what-does-if-name-main-do about what is going on. The first answer gives an explicit explanation and show case. – Cow Feb 24 '22 at 12:06

1 Answers1

2

Behaviour will depend on your operating system. On macOS (for example) you will get similar output to what you've shown.

However, if you do this:

from multiprocessing import Pool

def methodUsingPool(x):
    with Pool() as pool:
        pool.map(print, x)

if __name__ == '__main__':
    methodUsingPool("x")
    print("1")

...you'll get your expected output regardless of platform

See: Python 3 multiprocessing

DarkKnight
  • 19,739
  • 3
  • 6
  • 22