我有/ cgroup / cpuset / set1。 set1有2-5,8。我想将一个进程绑定到该cpuset,然后将该进程中的一个线程固定到核心4.Cpuset的名称和线程名称以及我应该绑定线程的核心位于m配置文件中。是否有任何C API来解析cpuset?使用C代码实现固定的正确方法是什么?
答案 0 :(得分:9)
查看pthread_setaffinity_np
和pthread_getaffinity_np
函数。
示例:
#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);
}
有关详细信息,请参阅man page。
答案 1 :(得分:3)
调用以下函数并传递您要传递的任何核心ID。此外,无论您何时调用此函数,都要检查其返回值为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;
}