为进程分配 cpu 个核心 - Linux

Assigning a cpu core to a process - Linux

有什么方法可以强制执行具有特定 PID 的进程,并且 运行 仅在服务器的 cpu 之一上执行?我知道有这样的命令

taskset -cp <Cpu_Number> <Pid>

但是上面的命令在我的系统上不起作用。所以请让我知道是否有任何其他命令。

有两种方法可以将 cpu core/cores 分配给 运行 进程。

第一种方法:

taskset -cp 0,4 9030

很清楚!将 cpu 核心 0 和 4 分配给 pid 9030。

第二种方法:

taskset -p 0x11 9030

这有点复杂。 -p 后面的十六进制数是位掩码。可以找到解释 here,摘录如下:

The CPU affinity is represented as a bitmask, with the lowest order bit corresponding to the first logical CPU and the highest order bit corresponding to the last logical CPU. Not all CPUs may exist on a given system but a mask may specify more CPUs than are present. A retrieved mask will reflect only the bits that correspond to CPUs physically on the system. If an invalid mask is given (i.e., one that corresponds to no valid CPUs on the current system) an error is returned. The masks are typically given in hexadecimal.

还在迷茫?看下图:

我添加了十六进制数对应的二进制文件,处理器从零开始从左数。在第一个示例中,位掩码中有一个 one 对应于第 zero 个处理器,因此将为进程启用该处理器。所有在位掩码中相应位置具有 zero 的处理器都将被禁用。事实上,这就是它被称为面具的原因。

综上所述,使用任务集更改处理器亲和力需要:

A user must possess CAP_SYS_NICE to change the CPU affinity of a process. Any user can retrieve the affinity mask.

请检查Capabalities Man Page

您可能有兴趣查看此 SO Question,它涉及 CAP_SYS_NICE。

我的资源

  1. 教程 点

  2. XModulo