在 multiprocessing.Pool 中设置每个进程的 niceness

jsj*_*jsj 7 python nice multiprocessing

我怎样才能为 a 中的每个进程设置好感multiprocessing.Pool?我知道我可以增加 niceness os.nice(),但是在创建池后如何在子进程中调用它?如果我在映射函数中调用它,它将在每次函数执行时调用,而不是在进程分叉时调用一次。

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)
Run Code Online (Sandbox Code Playgroud)

Mar*_*arc 6

为此使用初始化器怎么样?https://docs.python.org/3.8/library/multiprocessing.html#multiprocessing.pool.Pool 该函数在池启动时调用一次,因此初始化程序中的 os.nice() 调用设置进程的良好程度在那之后。

我添加了一些额外的语句来表明它可以在您的工作函数中工作,但 os.nice() 调用显然应该被删除,因为您想要一个静态的好值。

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)
Run Code Online (Sandbox Code Playgroud)

正如您从打印中看到的,niceness 现在从 3 开始(我已将其设置为 NICENESS),并从那里开始递增。

或者作为可用的片段

import multiprocessing as mp
import os

NICENESS = 3


def mp_function(bar: int) -> int:
    return bar * 2


if __name__ == '__main__':
    pool = mp.Pool(3, initializer=os.nice, initargs=(NICENESS,))
    data = range(6)
    pool.map(mp_function, data)
Run Code Online (Sandbox Code Playgroud)