Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pinning a thread to a core in a cpuset through C

Tags:

c

linux

cpu

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?

like image 834
Prashanth Avatar asked Sep 18 '15 17:09

Prashanth


2 Answers

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.

like image 144
dbush Avatar answered Sep 19 '22 21:09

dbush


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;
}
like image 41
Ankur Chauhan Avatar answered Sep 19 '22 21:09

Ankur Chauhan