如何为 multiprocessing.Pool
中的每个进程设置 niceness ?我知道我可以用 os.nice()
增加友好度,但是在创建池后如何在子进程中调用它?如果我在映射函数中调用它,它将在每次函数执行时调用,而不是在进程 fork 时调用一次。
import multiprocessing as mp
NICENESS = 19
DATA = range(100000)
def foo(bar):
return bar * 2
pool = mp.Pool(100)
# Somehow set niceness of each process to NICENESS
pool.map(foo, DATA)
最佳答案
为此使用初始化程序怎么样? https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.pool
我相信该函数在池启动时被调用一次,我猜初始化器中的 os.nice() 调用应该适用于之后的过程。
我已经添加了一些额外的语句来表明它在你的工作函数中工作,但是 os.nice() 调用显然应该被删除,因为你想要一个静态的 niceness 值。
import multiprocessing as mp
import os
NICENESS = 3
DATA = range(6)
def foo(bar):
newniceness = os.nice(1) # remove this
print('Additional niceness:', newniceness) # remove this
return bar * 2
def set_nicesness(val): # the initializer
newval = os.nice(val) # starts at 0 and returns newvalue
print('niceness value:', newval)
pool = mp.Pool(3, initializer=set_nicesness, initargs=(NICENESS,))
# Somehow set niceness of each process to NICENESS
pool.map(foo, DATA)
正如你从打印中看到的,niceness 现在从 3 开始(我已经为 NICENESS 设置了这个)并从那里开始增加。
关于python - 在 multiprocessing.Pool 中设置每个进程的 niceness,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59579859/