在Linux中如何将服务绑定在某个CPU内核上运行?
如果服务是多线程服务,那么它可能会根据线程的可用性在多个核心上运行,
如果该服务在单个核心上运行,则每次重新启动服务时它将在不同的线程上运行,但至少它会继续使用单线程直到该服务重新启动。
在 Linux 中如何找出进程运行在哪个CPU核心上
如何将指定的CPU核心分配给服务?
例如我有一个 test.service
# systemctl status test.service â test.service - LSB: start any SW, when required Loaded: loaded (/etc/rc.d/init.d/test; enabled; vendor preset: disabled) Active: active (exited) since Sun 2015-01-21 00:04:55 IST; 31s ago Docs: man:systemd-sysv-generator(8) Process: 22045 ExecStop=/etc/rc.d/init.d/test stop (code=exited, status=0/SUCCESS) Process: 22066 ExecStart=/etc/rc.d/init.d/test start (code=exited, status=0/SUCCESS)
使用以下命令,我们可以检查它正在使用的核心
# grep -i cpu /proc/2206?/status Cpus_allowed: 1000 Cpus_allowed_list: 12
现在,如果我重新启动 servcie 并检查服务的 PID,我们将观察到核心编号很可能会发生变化
# systemctl status test.service â test.service - LSB: start any SW, when required Loaded: loaded (/etc/rc.d/init.d/test; enabled; vendor preset: disabled) Active: active (exited) since Sun 2015-01-21 00:06:07 IST; 7s ago Docs: man:systemd-sysv-generator(8) Process: 22290 ExecStop=/etc/rc.d/init.d/test stop (code=exited, status=0/SUCCESS) Process: 22312 ExecStart=/etc/rc.d/init.d/test start (code=exited, status=0/SUCCESS)
正如我们之前看到的,此服务在第 12 个核心上运行,现在它在第 6 个核心上运行。
# grep -i cpu /proc/2231?/status Cpus_allowed: 0040 Cpus_allowed_list: 6
将此服务分配给我们希望始终运行的核心
# vim /etc/systemd/system/test.service ... [Service] CPUAffinity=13 Type=forking Restart=no ...
由于我们修改了单元文件我们必须在重新启动服务之前刷新配置
# systemctl daemon-reload # systemctl restart test.service
接下来检查服务的状态和PID
# systemctl status test.service â test.service - LSB: start any SW, when required Loaded: loaded (/etc/rc.d/init.d/test; enabled; vendor preset: disabled) Active: active (exited) since Sun 2015-01-21 00:01:51 IST; 2s ago Docs: man:systemd-sysv-generator(8) Process: 21944 ExecStop=/etc/rc.d/init.d/test stop (code=exited, status=0/SUCCESS) Process: 21966 ExecStart=/etc/rc.d/init.d/test start (code=exited, status=0/SUCCESS)
正如预期的那样,现在该服务正在分配的核心上运行,
# grep -i cpu /proc/2196?/status Cpus_allowed: 2000 Cpus_allowed_list: 13
让我们把它改成不同的核心编号
# vim /etc/systemd/system/test.service ... [Service] CPUAffinity=15 Type=forking Restart=no ...
接着是重新加载单元配置文件并重启各自的服务
# systemctl daemon-reload # systemctl restart test.service
接下来检查服务的状态和PID
# systemctl status test.service â test.service - LSB: start any SW, when required Loaded: loaded (/etc/rc.d/init.d/test; enabled; vendor preset: disabled) Active: active (exited) since Sat 2015-01-20 23:59:14 IST; 13s ago Docs: man:systemd-sysv-generator(8) Process: 21760 ExecStop=/etc/rc.d/init.d/test stop (code=exited, status=0/SUCCESS) Process: 21782 ExecStart=/etc/rc.d/init.d/test start (code=exited, status=0/SUCCESS)
使用以下命令,我们获取运行此测试服务的核心,并按预期在第 15 个核心上运行
# grep -i cpu /proc/2178?/status Cpus_allowed: 8000 Cpus_allowed_list: 15
日期:2020-06-02 22:16:53 来源:oir作者:oir