在多进程池中设置每个进程的优先级

10
我怎样可以为multiprocessing.Pool中的每个进程设置优先级?我知道可以通过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)

这个回答是否解决了你的问题?多进程和niceness值 - quamrana
1
很遗憾,我不能这样做,因为我不想在映射函数中调用它,而是在池创建时调用。 - jsj
2个回答

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

我添加了一些附加语句以显示它在您的工作函数中运行,但是由于您想要一个静态niceness值,因此显然应删除 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)

从输出的结果中可以看出,现在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)

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运行,因为有些东西不能提升其他进程。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接