为了账号安全,请及时绑定邮箱和手机立即绑定

如何设置特定pthread的CPU亲和力?

如何设置特定pthread的CPU亲和力?

繁星coding 2019-12-12 13:03:52
我想指定特定pthread的cpu亲和力。到目前为止,我发现的所有引用都涉及设置进程(pid_t)而不是线程(pthread_t)的cpu亲和力。我尝试了一些传递pthread_t的实验,并且按预期它们会失败。我是否在尝试做一些不可能的事情?如果没有,您可以发送指针吗?太感谢了。
查看完整描述

3 回答

?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

这是我为了使生活更轻松而制作的包装纸。它的作用是使调用线程被“塞住”到具有id的内核core_id:


// core_id = 0, 1, ... n-1, where n is the system's number of cores


int stick_this_thread_to_core(int core_id) {

   int num_cores = sysconf(_SC_NPROCESSORS_ONLN);

   if (core_id < 0 || core_id >= num_cores)

      return EINVAL;


   cpu_set_t cpuset;

   CPU_ZERO(&cpuset);

   CPU_SET(core_id, &cpuset);


   pthread_t current_thread = pthread_self();    

   return pthread_setaffinity_np(current_thread, sizeof(cpu_set_t), &cpuset);

}


查看完整回答
反对 回复 2019-12-12
?
慕容3067478

TA贡献1773条经验 获得超3个赞

假设Linux:


设置相似性的界面是-您可能已经发现:


int sched_setaffinity(pid_t pid,size_t cpusetsize,cpu_set_t *mask);

传递0作为pid,它将仅适用于当前线程,或者让其他线程通过linux特定的调用报告其内核pid pid_t gettid(void);并将其作为pid传递。


引用手册页


亲和力掩码实际上是每个线程的属性,可以针对线程组中的每个线程分别进行调整。调用gettid(2)返回的值可以在pid参数中传递。将pid指定为0将为调用线程设置属性,并将从调用返回的值传递给getpid(2)将为线程组的主线程设置属性。(如果使用的是POSIX线程API,请使用pthread_setaffinity_np(3)而不是sched_setaffinity()。)


查看完整回答
反对 回复 2019-12-12
?
倚天杖

TA贡献1828条经验 获得超3个赞

//compilation: gcc -o affinity affinity.c -lpthread


#define _GNU_SOURCE

#include <sched.h>   //cpu_set_t , CPU_SET

#include <pthread.h> //pthread_t

#include <stdio.h>


void *th_func(void * arg); 


int main(void) {

  pthread_t thread; //the thread


  pthread_create(&thread,NULL,th_func,NULL); 


  pthread_join(thread,NULL);   


  return 0;

}



void *th_func(void * arg)

{  

  //we can set one or more bits here, each one representing a single CPU

  cpu_set_t cpuset; 


  //the CPU we whant to use

  int cpu = 2;


  CPU_ZERO(&cpuset);       //clears the cpuset

  CPU_SET( cpu , &cpuset); //set CPU 2 on cpuset



  /*

   * cpu affinity for the calling thread 

   * first parameter is the pid, 0 = calling thread

   * second parameter is the size of your cpuset

   * third param is the cpuset in which your thread will be

   * placed. Each bit represents a CPU

   */

  sched_setaffinity(0, sizeof(cpuset), &cpuset);


  while (1);

       ; //burns the CPU 2


  return 0;

}

在POSIX环境中,可以使用cpusets来控制进程或pthread可以使用哪些CPU。这种类型的控制称为CPU关联。


函数“ sched_setaffinity”接收pthread ID和cpuset作为参数。当您在第一个参数中使用0时,调用线程将受到影响


查看完整回答
反对 回复 2019-12-12
  • 3 回答
  • 0 关注
  • 875 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信