1

I am new to multiprocessing. i wrote a simple code that takes 1 number at a time and print it.

import multiprocessing as mp

def test(num):
    print num

L = [1,2,3,4,5,6,7,8]


pool = mp.Pool(2)
pool.map(test,L)

this can be done using normal method also [test(i) for i in L]

But i want to use multiprocessing and do this. But when i am running the program, the kernal shows busy, but no prints are happening.

Is there something wrong in my code?

Shubham R
  • 7,382
  • 18
  • 53
  • 119
  • Are you using windows? – Ilja Everilä Jun 16 '17 at 11:22
  • @IljaEverilä yes – Shubham R Jun 16 '17 at 11:24
  • You have an infinite loop as a result of multiprocessing trying to spawn new processes that try to import the test function from your module, which causes a new set of processes to spawn and... You need to guard the actual "main" code with `if __name__ == "__main__": ...` in order to prevent that. On systems that support forking, such as linux, this does not happen as they just fork on the spot and call the function. – Ilja Everilä Jun 16 '17 at 11:27
  • @IljaEverilä i didn't get you? you mean `import test` , but where do i save test.py ? – Shubham R Jun 16 '17 at 11:28
  • Move everything but the function test in an if-statement that ensures that the guarded code is not run when someone or something is just trying to import the function test. The way multiprocessing works on windows is that it spawns entirely new processes that import your function in order to do the work. The code in the if block should run only when your module is the main module. – Ilja Everilä Jun 16 '17 at 11:34
  • Read https://stackoverflow.com/questions/419163/what-does-if-name-main-do – Ilja Everilä Jun 16 '17 at 11:36

1 Answers1

-1

When I run your code in terminal(Python2.7.6) and it prints

1
3
2
4
5
6
7
8
[None, None, None, None, None, None, None, None]
RaTh0D
  • 323
  • 3
  • 19