Pinning a thread to a core in a cpuset through C

前端 未结 2 1287
慢半拍i
慢半拍i 2021-02-14 05:11

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

2条回答
  •  忘掉有多难
    2021-02-14 05:23

    Take a look at the pthread_setaffinity_np and pthread_getaffinity_np functions.

    Example:

       #define _GNU_SOURCE
       #include 
       #include 
       #include 
       #include 
    
       #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.

提交回复
热议问题