Linux:查看线程运行于哪个CPU核心上

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/test1280/article/details/87993669
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.
1
方法二:top -Hp $pid 并修改监控字段
1.执行 top -Hp $pid

[test1280@localhost 20190227]$ top -Hp 11819
1

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
 ———————————————— 
版权声明:本文为CSDN博主「test1280」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/test1280/article/details/87993669

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值