在多处理模块中使用 Pool 修改全局变量
Modify global variable with Pool in multiprocessing module
我不熟悉多处理模块。我正在尝试验证不同过程中的变量是否无关紧要。经过测试,我发现不同的进程大概有"share"个变量。当进程具有相同的 pid 时会发生这种情况。不知道有没有关系?
环境:Windows10; python3.7
# -*- coding: utf-8 -*-
import os
from multiprocessing import Pool
p=0
def Child_process(id_number):
global p
print('Task start: %s(%s)' % (id_number, os.getpid()))
print('p = %d' % p)
p=p+1
print('Task {} end'.format(id_number))
if __name__ == '__main__':
p = Pool(4)
p.map(Child_process,range(5))
p.close()
p.join()
结果是:
任务开始:0(7668)
p = 0
任务开始:1(10384)
任务 0 结束
p = 0
任务开始:2(7668)
p = 1
任务 1 结束
任务 2 结束
任务开始:3(7668)
任务开始:4(10384)
p = 1
任务 4 结束
p = 2
任务 3 结束
我认为p应该一直为0,但是当不同的进程具有相同的pid时它会增加?
根据定义,thread/process 池将 re-use 相同 thread/process。这使您可以在 thread/process 启动时设置资源,这样每个 thread/process 就不必每次都初始化它们。这包括全局变量、打开的文件、套接字等。您可以通过将 initializer
函数传递给 thread/process 来进行一次性初始化。因此,如果您设置或增加变量 p
,它将在整个过程的各个 运行 中保持设置。如果您希望每个 运行 的变量始终从 0 开始,则需要在每个 运行 的开头将其设置为 0。
此注释在 multiprocessing.pool.Pool class:
Note: Worker processes within a Pool typically live for the complete duration of the Pool’s work queue. A frequent pattern found in other systems (such as Apache, mod_wsgi, etc) to free resources held by workers is to allow a worker within a pool to complete only a set amount of work before being exiting, being cleaned up and a new process spawned to replace the old one. The maxtasksperchild argument to the Pool exposes this ability to the end user.
我不熟悉多处理模块。我正在尝试验证不同过程中的变量是否无关紧要。经过测试,我发现不同的进程大概有"share"个变量。当进程具有相同的 pid 时会发生这种情况。不知道有没有关系?
环境:Windows10; python3.7
# -*- coding: utf-8 -*-
import os
from multiprocessing import Pool
p=0
def Child_process(id_number):
global p
print('Task start: %s(%s)' % (id_number, os.getpid()))
print('p = %d' % p)
p=p+1
print('Task {} end'.format(id_number))
if __name__ == '__main__':
p = Pool(4)
p.map(Child_process,range(5))
p.close()
p.join()
结果是:
任务开始:0(7668)
p = 0
任务开始:1(10384)
任务 0 结束
p = 0
任务开始:2(7668)
p = 1
任务 1 结束
任务 2 结束
任务开始:3(7668)
任务开始:4(10384)
p = 1
任务 4 结束
p = 2
任务 3 结束
我认为p应该一直为0,但是当不同的进程具有相同的pid时它会增加?
根据定义,thread/process 池将 re-use 相同 thread/process。这使您可以在 thread/process 启动时设置资源,这样每个 thread/process 就不必每次都初始化它们。这包括全局变量、打开的文件、套接字等。您可以通过将 initializer
函数传递给 thread/process 来进行一次性初始化。因此,如果您设置或增加变量 p
,它将在整个过程的各个 运行 中保持设置。如果您希望每个 运行 的变量始终从 0 开始,则需要在每个 运行 的开头将其设置为 0。
此注释在 multiprocessing.pool.Pool class:
Note: Worker processes within a Pool typically live for the complete duration of the Pool’s work queue. A frequent pattern found in other systems (such as Apache, mod_wsgi, etc) to free resources held by workers is to allow a worker within a pool to complete only a set amount of work before being exiting, being cleaned up and a new process spawned to replace the old one. The maxtasksperchild argument to the Pool exposes this ability to the end user.