在多进程线程之前和之后发出运行代码

时间:2017-03-21 22:38:34

标签: python multithreading multiprocessing

您好所有这些代码都会运行,但第二个print语句在工作线程之后没有执行。

import multiprocessing

def worker(num):
    """thread worker function"""
    print 'Worker:', num
    return

if __name__ == '__main__':
     jobs = []

     print 'starting for loop'
     for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i,))
        jobs.append(p)
        p.start()
     print 'after for loop'

我得到的是输出:

starting for loop
Worker: 1
after for loop
Worker: 0
Worker: 3
Worker: 4
Worker: 2

1 个答案:

答案 0 :(得分:3)

 for i in range(5):
    p = multiprocessing.Process(target=worker, args=(i,))
    jobs.append(p)
    p.start()
 for p in jobs:
     p.join()  # wait for the process to finish
 print 'after for loop'

或更简单:

 print 'starting pool'
 Pool().map(worker, range(5))
 print 'after pool'