You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

sched_getcpu()返回CPU编号范围疑问及与物理线程对应关系咨询

关于Pthread线程CPU编号的疑惑解答

嘿,作为Pthread新手能写出这样的测试代码已经很棒啦!我来帮你理清你遇到的两个问题~

为什么输出的CPU编号范围是0-3?

你的电脑是2核4线程,这里的“4线程”其实是超线程(Hyper-Threading)技术带来的逻辑CPU。简单来说,每个物理核心可以模拟出两个独立的逻辑执行单元,操作系统会把这些逻辑单元当成独立的CPU来管理和调度。所以你的系统实际上识别到了4个逻辑处理器,它们的编号从0开始计数,自然就是0-3啦,这就是你输出范围的原因。

输出的CPU编号是否与物理线程ID对应?

sched_getcpu()返回的是当前线程正在运行的逻辑CPU的编号,这个编号和系统里的逻辑处理器是一一对应的,而你说的“物理线程ID”其实就是这些逻辑CPU,所以是对应的。

不过要注意,内核的调度器会根据系统负载动态把线程调度到不同的逻辑CPU上,所以每次运行程序输出的编号不一样是完全正常的——这正是调度器在合理分配资源的表现。

附你的测试代码(格式化后)

#include <pthread.h>
#include <stdio.h>

void* a(){ 
    printf("1st child thread in CPU %d\n",sched_getcpu()); 
    return NULL; 
}
void* b(){ 
    printf("2nd child thread in CPU %d\n",sched_getcpu()); 
    return NULL; 
}
void* c(){ 
    printf("3rd child thread in CPU %d\n",sched_getcpu()); 
    return NULL; 
}
void* d(){ 
    printf("4th child thread in CPU %d\n",sched_getcpu()); 
    return NULL; 
}
void* e(){ 
    printf("5th child thread in CPU %d\n",sched_getcpu()); 
    return NULL; 
}

int main(){ 
    pthread_t t, t1, t2, t3, t4; 
    pthread_create(&t,NULL,a,NULL); 
    pthread_create(&t1,NULL,b,NULL); 
    pthread_create(&t2,NULL,c,NULL); 
    pthread_create(&t3,NULL,d,NULL); 
    pthread_create(&t4,NULL,e,NULL); 
    
    pthread_join(t,NULL); 
    pthread_join(t1,NULL); 
    pthread_join(t2,NULL); 
    pthread_join(t3,NULL); 
    pthread_join(t4,NULL); 
    
    printf("main thread in CPU %d\n",sched_getcpu()); 
    return 0; 
}

小补充:如果想让线程固定运行在某个逻辑CPU上,可以试试pthread_setaffinity_np()函数,这样就能测试固定CPU后的输出啦~

内容的提问来源于stack exchange,提问作者PhanDC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:31:05