Pinning a thread to a core in a cpuset through C

2020-06-11 06:21发布

I have /cgroup/cpuset/set1. set1 has 2-5,8. I want to bind a process to that cpuset and then pin a thread in that process to, say, core 4. The name of the cpuset and the thread name and the core to which I should bind the thread is in m config file. Are there any C APIs to parse cpuset? What is the correct way to achieve the pinning using C code?

标签: c linux cpu
2条回答
聊天终结者
2楼-- · 2020-06-11 07:02

Take a look at the pthread_setaffinity_np and pthread_getaffinity_np functions.

Example:

   #define _GNU_SOURCE
   #include <pthread.h>
   #include <stdio.h>
   #include <stdlib.h>
   #include <errno.h>

   #define handle_error_en(en, msg) \
           do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)

   int
   main(int argc, char *argv[])
   {
       int s, j;
       cpu_set_t cpuset;
       pthread_t thread;

       thread = pthread_self();

       /* Set affinity mask to include CPUs 0 to 7 */

       CPU_ZERO(&cpuset);
       for (j = 0; j < 8; j++)
           CPU_SET(j, &cpuset);

       s = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
       if (s != 0)
           handle_error_en(s, "pthread_setaffinity_np");

       /* Check the actual affinity mask assigned to the thread */

       s = pthread_getaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
       if (s != 0)
           handle_error_en(s, "pthread_getaffinity_np");

       printf("Set returned by pthread_getaffinity_np() contained:\n");
       for (j = 0; j < CPU_SETSIZE; j++)
           if (CPU_ISSET(j, &cpuset))
               printf("    CPU %d\n", j);

       exit(EXIT_SUCCESS);
   }

For more details, see the man page.

查看更多
老娘就宠你
3楼-- · 2020-06-11 07:04

Call the following Function and pass whatever core ID you want to pass. Also from wherever you call this function do check its return value to be 1.

short CorePin(int coreID)
{
  short status=0;
  int nThreads = std::thread::hardware_concurrency();
  //std::cout<<nThreads;
  cpu_set_t set;
  std::cout<<"\nPinning to Core:"<<coreID<<"\n";
  CPU_ZERO(&set);

  if(coreID == -1)
  {
    status=-1;
    std::cout<<"CoreID is -1"<<"\n";
    return status;
  }

  if(coreID > nThreads)
  {
    std::cout<<"Invalid CORE ID"<<"\n";
    return status;
  }

  CPU_SET(coreID,&set);
  if(sched_setaffinity(0, sizeof(cpu_set_t), &set) < 0)
  {
    std::cout<<"Unable to Set Affinity"<<"\n";
    return -1;
  }
  return 1;
}
查看更多
登录 后发表回答