简体   繁体   English

在python中使用多进程时子进程会做什么

[英]What will subprocesses do when using multiprocess in python

I'm now learning multiprocess library in python, so I design some experiments to see how does the overall process proceed.我现在正在学习python中的多进程库,所以我设计了一些实验来看看整个过程是如何进行的。 I'm confused about the experiment below.我对下面的实验感到困惑。 The first question is why the value of link_id that each subprocess uses is still 0. The second question is why line3-line6 has been conducted many times (9 times in my case), and it is not equal to the number of subprocesses I have.第一个问题是为什么每个子进程使用的link_id的值仍然是0。第二个问题是为什么line3-line6进行了很多次(我的例子是9次),并且不等于我拥有的子进程数. Python version: 3.7.4, Operation system: win10 Python版本:3.7.4,操作系统:win10

from multiprocessing import Pool

link_id = 0
print('head is printing link, value {}, id {}'.format(link_id,id(link_id)))
node_id = 0
print('head is printing node, value {}, id {}'.format(node_id,id(node_id)))

def job(i):
    print('job {} is printing link, value {}, var id {}'.format(i,link_id,id(link_id)))    

def mainFunc():

    p = Pool()
    for i in range(20): p.apply_async(job, args=(i,))
    p.close()
    p.join()


if __name__ == '__main__':
    link_id = 10
    print('main is printing link, value {}, id {}'.format(link_id,id(link_id)))
    mainFunc()
    print('main is printing link, value {}, id {}'.format(link_id,id(link_id)))

Why is value of link_id that each subprocess uses 0 ?为什么每个子进程使用的link_id值是0

Each subprocess is an instance of the python interpreter, each one will run/compile your script and have a separate reference to the module.每个子进程都是 python 解释器的一个实例,每个子进程都将运行/编译你的脚本并有一个对模块的单独引用。 __name__ == '__main__' will be False though as this is only True when you run the file directly, so link_id will be 0 for each of these subprocesses __name__ == '__main__'将是False因为这仅在您直接运行文件时才为True ,因此对于这些子link_id中的每一个, link_id将为0

Why is line3-line6 conducted many times为什么line3-line6进行多次

The answer to this is the same as the first, the lines will be run number_of_subprocesses + 1 times (the additional 1 is when you run the script).答案与第一个相同,这些行将运行number_of_subprocesses + 1次(额外的 1 次是在您运行脚本时)。 If you change the number of processes in the pool you should see the number of times the lines are run change如果您更改池中的进程数,您应该会看到行运行的次数发生变化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM