为此使用初始化程序怎么样?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)并从那里开始递增。