我试图在脚本的开头编写一些代码,以确保脚本中的每个命令仅在几个特定的核心上运行。即使许多命令以多个并行方式运行,例如: [command] & [command] & [command] & [command] & [command] ,我希望它们仅在少数选定的核心上运行。
目前,该脚本在启动时会查找自己的 PID,然后将其输入到任务集中,我告诉它它的 PID 只允许使用核心 1 到 3。
示例任务集命令如下所示:
taskset -c 1-3 -p 45678
但是,一旦某些并行命令启动,它们每个都会获得自己的 PID,并且不再局限于分配的内核。
如何确保脚本中的所有内容都保留在所需的核心中?
答案1
如果为调用进程设置 CPU,那么看起来每个子进程都会有相同的设置。
例如,给定:
screen
使用启动的会话taskset 4 screen
在会话中,启动了
screen
3 个实例top
当我(在另一个终端中)查看top
实例的状态时:
for pid in $(ps aux|grep -i top|grep -v grep|awk '{print $2}') ; do taskset -p ${pid} ; done
pid 2505's current affinity mask: 4
pid 2515's current affinity mask: 4
pid 2525's current affinity mask: 4
下面是执行此操作的 bash 脚本的示例:
#!/bin/bash
echo "Setting CPU affinity ..."
# Bind to a given CPU
taskset -p 4 $$
# Verify it worked
taskset -p $$
echo "Launching background jobs ..."
# Now, launch several background jobs
for i in $(seq 0 10) ; do
tail -f /dev/null &
done
echo "Checking ..."
# Now for each instance of background jobs, check CPU affinity
for pid in $(pidof tail) ; do
taskset -p ${pid}
done
sleep 1
killall tail
结果输出:
Setting CPU affinity ...
pid 4313's current affinity mask: f
pid 4313's new affinity mask: 4
pid 4313's current affinity mask: 4
Launching background jobs ...
Checking ...
pid 4327's current affinity mask: 4
pid 4326's current affinity mask: 4
pid 4325's current affinity mask: 4
pid 4324's current affinity mask: 4
pid 4323's current affinity mask: 4
pid 4322's current affinity mask: 4
pid 4321's current affinity mask: 4
pid 4320's current affinity mask: 4
pid 4319's current affinity mask: 4
pid 4318's current affinity mask: 4
./test.sh: line 24: 4317 Terminated tail -f /dev/null
./test.sh: line 24: 4318 Terminated tail -f /dev/null
./test.sh: line 24: 4319 Terminated tail -f /dev/null
./test.sh: line 24: 4320 Terminated tail -f /dev/null
./test.sh: line 24: 4321 Terminated tail -f /dev/null
./test.sh: line 24: 4322 Terminated tail -f /dev/null
./test.sh: line 24: 4323 Terminated tail -f /dev/null
./test.sh: line 24: 4324 Terminated tail -f /dev/null
./test.sh: line 24: 4325 Terminated tail -f /dev/null
./test.sh: line 24: 4326 Terminated tail -f /dev/null
./test.sh: line 24: 4327 Terminated tail -f /dev/null