8

如何为 a 中的每个进程设置 niceness 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)
4

2 回答 2

4

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

于 2020-01-03T15:54:01.557 回答
0

您可以通过 访问工作进程pool._pool。有了这个,您可能可以单独设置每个工人的友好度。

import time
import psutil
import multiprocessing as mp
NICENESS =19
DATA = range(15)

def foo(bar):
    time.sleep(bar)
    return bar*2
if __name__=='__main__':
    pool = mp.Pool(8) # 100 might not make sense if you only have 8 cores

    processes = [p.pid for p in pool._pool]
    for pid in processes:
        p = psutil.Process(pid)
        p.nice(NICENESS) # POSIX
        # use this for Windows: 
        # p.nice(psutil.HIGH_PRIORITY_CLASS)
    pool.map(foo, DATA)

我无法在 Linux 上测试它,因为我在 Windows 上,但在这里它运行良好。让我知道它是否适用于 Linux。可能是您需要将父进程作为 运行sudo,因为有些东西无法提升其他进程。

于 2020-01-03T14:21:37.843 回答