Reputation: 21
I have been studying multiprocessing module in Python for few days.
However, I have met a strange problem that I cannot resolve it.
The source code is very simple but I cannot get any results after running this code.
The code is as follows:
import multiprocessing as multi
def worker():
print "Worker!!!"
return
jobs = []
for i in range(5):
p = multi.Process(target = worker)
jobs.append(p)
p.start()
I was expecting to get a five time of printing "Worker!!!".
However, the only thing I've got is
* Remote Interpreter Reinitialized *
">>>"
">>>"
Does anybody who has a idea to solve this problem??
Please DO HELP ME!!!
Upvotes: 2
Views: 5495
Reputation: 369074
According to multiprocessing documentation
:
Note
Functionality within this package requires that the __main__ module be importable by the children. This is covered in Programming guidelines however it is worth pointing out here. This means that some examples, such as the multiprocessing.Pool examples will not work in the interactive interpreter.
...
Safe importing of main module
Make sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new process).
...
one should protect the “entry point” of the program by using if __name__ == '__main__'
So your program should read as follow:
import multiprocessing as multi
def worker():
print "Worker!!!"
if __name__ == '__main__':
jobs = []
for i in range(5):
p = multi.Process(target = worker)
jobs.append(p)
p.start()
for job in jobs:
job.join()
Upvotes: 1