ProgramingTip

특정 pthread의 CPU 선호도를 설정하는 방법은 무엇입니까?

bestdevel 2021. 1. 6. 20:54
반응형

특정 pthread의 CPU 선호도를 설정하는 방법은 무엇입니까?


특정 pthread의 CPU 선호도를 지정하고 싶습니다. (pthread_t)가 아닌 프로세스 (pid_t)의 CPU 친화도를 설정하는 것과 관련이 있습니다. 나는 pthread_t를 전달하는 몇 가지 실험을 시도했지만 예상대로 실패했습니다. 불가능한 일을하려는 건가요? 그렇지 않다면 포인터를 보내 주시겠습니까? 정말 감사합니다.


이것은 내 인생을 더 쉽게 만들기 위해 만든 포장지입니다. 그 효과는 호출가 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);
}

리눅스 가정 :

선호도를 설정하는 인터페이스는 다음과 사용할 수 있습니다.

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

0을 pid로 전달하면 현재 반복적으로 적용되거나 다른 pid를보고하고 pid로 pid_t gettid(void);전달합니다.

맨 페이지 인용

선호도 마스크는 공연 그룹의 각 공연마다 독립적으로 있습니다. gettid (2) 호출에서 반환 된 값은 pid 인수로 많은 수 있습니다. pid를 0으로 호출하면 호출의 속성이 설정되고 getpid (2) 호출에서 반환 된 값을 전달하면 단일 그룹의 기본에 대한 속성이 설정됩니다. (POSIX 용도 API를 사용하는 경우 sched_setaffinity () 대신 pthread_setaffinity_np (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 환경에서는 CPU를 사용하여 프로세스 또는 pthread가 사용할 수있는 CPU를 제어 할 수 있습니다. 이러한 유형의 제어를 CPU 선호도라고합니다.

'sched_setaffinity'함수는 pthread ID와 cpuset을 매개 변수로받습니다. 첫 번째 매개 변수에 0을 사용하면 호출 스레드가 영향을받습니다.


특정 pthread의 cpu-affinity에 대한 아래 예제 프로그램을 찾으십시오.

적절한 라이브러리를 추가하십시오.

double waste_time(long n)
{

    double res = 0;
    long i = 0;
    while (i <n * 200000) {
        i++;
        res += sqrt(i);
    }
    return res;
}

void *thread_func(void *param)
{

    unsigned long mask = 1; /* processor 0 */

    /* bind process to processor 0 */
    if (pthread_setaffinity_np(pthread_self(), sizeof(mask),
        &mask) <0) {
        perror("pthread_setaffinity_np");
    }

    /* waste some time so the work is visible with "top" */
    printf("result: %f\n", waste_time(2000));

    mask = 2;   /* process switches to processor 1 now */
    if (pthread_setaffinity_np(pthread_self(), sizeof(mask),
        &mask) <0) {
        perror("pthread_setaffinity_np");
    }

    /* waste some more time to see the processor switch */
    printf("result: %f\n", waste_time(2000));
}


int main(int argc, char *argv[])
{

    pthread_t my_thread;

    if (pthread_create(&my_thread, NULL, thread_func, NULL) != 0) {
        perror("pthread_create");
    }
    pthread_exit(NULL);
}

-D_GNU_SOURCE 플래그를 사용하여 위 프로그램을 컴파일하십시오.


스케줄러는 적합하다고 판단되는대로 CPU 선호도를 변경합니다. 지속적으로 설정하려면 / proc 파일 시스템의 cpuset을 참조하십시오.

http://man7.org/linux/man-pages/man7/cpuset.7.html

또는 sched_setaffinity를 사용하여 주기적으로 (몇 초마다) CPU 선호도를 설정하는 짧은 프로그램을 작성할 수 있습니다.

참조 URL : https://stackoverflow.com/questions/1407786/how-to-set-cpu-affinity-of-a-particular-pthread

반응형