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

标签 python multiprocessing nice

如何为 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/

相关文章:

python - pycharm上pytorch 1.6.0安装问题

python - 使用 python 模块子进程的 pg_dump 和 pg_restore 密码

父导出上的 Python 多处理队列

linux - 压缩 Web Root : Why didn't nice reduce CPU load?

python - 使用模拟对象简化 Django 测试设置

python - 名称冲突使用 'from import' 而我不能使用导入的变量?

python - 嵌入式CPython,使用命名管道进行线程交互

Python - 使用多处理和按键检测

linux - "nice priority"对 iostat 命令的 %nice 意味着什么

linux - Linux IOnice 会影响/dev/nodes 吗?