Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/136.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 确定正在运行调用线程的CPU?_C++_C_Multithreading_Pthreads - Fatal编程技术网

C++ 确定正在运行调用线程的CPU?

C++ 确定正在运行调用线程的CPU?,c++,c,multithreading,pthreads,C++,C,Multithreading,Pthreads,我不熟悉Pthread。我已经写了一个例子来检查我的线程运行在哪个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(&q

我不熟悉Pthread。我已经写了一个例子来检查我的线程运行在哪个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;
     pthread_t t1;
     pthread_t t2;
     pthread_t t3;
     pthread_t 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的id号从0更改为3。我想知道为什么我的计算机只有2个内核和4个线程,而输出却在0到3之间。输出中CPU的id是否与物理线程的id相等?谢谢

您的计算机有2个内核和4个“逻辑处理器”(CPU)。因为您有4个CPU,所以ID号从0到3


这里的主要问题是术语——“CPU”(和“线程”)是如何定义的。您假设“CPU”定义为“核心”,但大多数人将其定义为“逻辑处理器”或(硬件)线程”;使用超线程时,每个核心有2个逻辑处理器,因此最终会有4个CPU(来自2个核心)。

注意:
sched_getcpu()
返回的值告诉您哪个CPU在某个特定时刻运行线程,但不能保证线程在以后的任何时间仍在同一CPU上运行。理论上,线程可能会丢失它的时间片,然后甚至在
sched_getcpu()
返回之前就被带回到另一个CPU上。这在实践中可能不会经常发生,但当I/O系统在随后的
printf(…)
complete中调用时,线程运行在不同CPU上的可能性会大大提高。这是非常有用的。谢谢分享!
1st child thread in CPU 2
3rd child thread in CPU 2
2nd child thread in CPU 0
4th child thread in CPU 3
5th child thread in CPU 1
main thread in CPU 3