Linux:查看线程运行于哪个CPU核心上
线程是最小的执行调度单元,线程执行于某个CPU核心之上,或者说某个CPU核心执行此线程。
如何查看某线程运行于哪个CPU核心上呢?
方法一:ps -eLF 查找 PSR 字段值
[test1280@localhost 20190227]$ ps -eLF
UID PID PPID LWP C NLWP SZ RSS PSR STIME TTY TIME CMD
root 1 0 1 0 1 4836 1548 2 Feb25 ? 00:00:02 /sbin/init
root 2 0 2 0 1 0 0 2 Feb25 ? 00:00:00 [kthreadd]
root 3 2 3 0 1 0 0 0 Feb25 ? 00:00:00 [migration/0]
……
测试代码:
main.c
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
void *start_routine(void *arg) {
const char *msg = "thread: i am thread";
while (1) {
write(1, msg, strlen(msg));
sleep(1);
}
}
int main() {
pthread_t tid;
pthread_create(&tid, NULL, start_routine, NULL);
const char *msg = "main: i am main\n";
while (1) {
write(1, msg, strlen(msg));
usleep(1000);
}
return 0;
}
运行输出:
[test1280@localhost 20190227]$ gcc -o main main.c -lpthread
[test1280@localhost 20190227]$ ./main
……
main: i am main
main: i am main
thread: i am threadmain: i am main
main: i am main
……
查看此进程中两个线程运行于哪个CPU核心上:
[test1280@localhost 20190227]$ pidof main
11819
[test1280@localhost 20190227]$ ps -eLF | grep 11819
test1280 11819 11053 11819 0 2 4115 476 2 13:43 pts/1 00:00:00 ./main
test1280 11819 11053 11820 0 2 4115 476 3 13:43 pts/1 00:00:00 ./main
test1280 11823 11468 11823 0 1 25829 844 2 13:43 pts/2 00:00:00 grep 11819
在 PID = 11819 的进程中:(参照 ps -eLF 输出字段顺序)
1)TID = 11819 的线程在执行 ps 命令时运行于 #2 CPU 核心上;
2)TID = 11820 的线程在执行 ps 命令时运行于 #3 CPU 核心上;
man ps
PSR processor that process is currently assigned to.
方法二:top -Hp $pid 并修改监控字段
1.执行 top -Hp $pid
[test1280@localhost 20190227]$ top -Hp 11819
2.键入 f(或者F)
3.键入 j(或者J)
4.回车确认 && 观察
我们发现,PID = 11819 的线程运行于 #3 CPU 核心上,与上次 ps -eLF 的 PSR 不同,发生了切换。
方法三:taskset -pc $pid
方法一、二都是执行查询命令那一时刻,执行进程(线程)运行于某CPU核心的快照。
方法一、二并不能反映出待查询线程能运行于哪些CPU核心,即可运行CPU核心的集合。
可通过 taskset -pc $pid 来获取某线程与CPU核心的亲和性(线程在运行中可能执行于CPU核心的集合)。
请参考 taskset 命令 查看。
参考资源:
1.https://blog.csdn.net/ibless/article/details/82431101
2.https://blog.csdn.net/rdc2008/article/details/41982963