I am a beginner in multiprocessing, can anyone tell me why this does not produce any output?
import multiprocessing
def worker(num):
"""thread worker function"""
print('Worker:', num)
if __name__ == '__main__':
jobs = []
for i in range(4):
p = multiprocessing.Process(target=worker, args=(i,))
jobs.append(p)
p.start()
You probably need to flush the output. You can use
sys.stdout.flush()
:You're starting your
Process()
, but never waiting on it to complete, so your program's execution ends before the background process finishes. Try this, with a call toProcess.join()
:Here we use
map()
to calljoin()
on each process in thejobs
list.Here's an example of this working:
As for why this isn't working in IDLE, see this answer: