多处理运行意外代码块

时间:2018-07-20 09:12:35

标签: python python-3.x multithreading

为什么该部分每次只能运行一次?这有意义吗?将目标函数作为单独的线程运行的正确方法是什么?

该代码摘自https://pymotw.com/2/multiprocessing/basics.html

上的一个非常简单的示例
import multiprocessing

print("Starting Main - This should only run ONCE")


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


if __name__ == '__main__':
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker1, args=(i,))
        jobs.append(p)
        print("Starting Process=", i)
        p.start()

输出控制台:

[Running] python "e:\Projects\Python-Test\test1.py"
Starting Main - This should only run ONCE
Starting Process= 0
Starting Process= 1
Starting Process= 2
Starting Process= 3
Starting Process= 4
Starting Main - This should only run ONCE # (??????? WHY )
Worker: 1
Starting Main - This should only run ONCE (???????)
Worker: 0
Starting Main - This should only run ONCE
Worker: 4
Starting Main - This should only run ONCE
Worker: 2
Starting Main - This should only run ONCE
Worker: 3

[Done] exited with code=0 in 0.45 seconds

0 个答案:

没有答案