通过C将线程固定到cpuset中的核心
我有/cgroup/cpuset/set1。set1有2-5,8。我想将一个进程绑定到该cpuset,然后将该进程中的一个线程固定到核心4。cpuset的名称、线程名称以及我应该绑定线程的核心在m config文件中。是否有任何C API来解析cpuset?使用C代码实现固定的正确方法是什么?查看通过C将线程固定到cpuset中的核心,c,linux,cpu,C,Linux,Cpu,我有/cgroup/cpuset/set1。set1有2-5,8。我想将一个进程绑定到该cpuset,然后将该进程中的一个线程固定到核心4。cpuset的名称、线程名称以及我应该绑定线程的核心在m config文件中。是否有任何C API来解析cpuset?使用C代码实现固定的正确方法是什么?查看pthread\u setaffinity\u np和pthread\u getaffinity\u np函数 例如: #define _GNU_SOURCE #include <pt
pthread\u setaffinity\u np
和pthread\u getaffinity\u 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);
}
定义GNU源
#包括
#包括
#包括
#包括
#定义句柄\u错误\u en(en,msg)\
do{errno=en;perror(msg);exit(exit_FAILURE);}while(0)
int
main(int argc,char*argv[])
{
int s,j;
cpu\u设置\u t cpuset;
pthread\u t线程;
thread=pthread_self();
/*将关联掩码设置为包括CPU 0到7*/
CPU_零(&cpuset);
对于(j=0;j<8;j++)
CPU_组(j和cpuset);
s=pthread\u setaffinity\u np(线程、大小f(cpu\u set\t)和cpuset);
如果(s!=0)
handle_error_en(s,“pthread_setaffinity_np”);
/*检查分配给线程的实际关联掩码*/
s=pthread\u getaffinity\u np(线程、大小f(cpu\u设置)&cpuset);
如果(s!=0)
handle_error_en(s,“pthread_getaffinity_np”);
printf(“由pthread_getaffinity_np()返回的集合包含:\n”);
对于(j=0;j
有关更多详细信息,请参阅。调用以下函数并传递您想要传递的任何核心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;
}
short CorePin(int-coreID)
{
短状态=0;
int nThreads=std::thread::hardware_concurrency();
//std::coutPossible dupe of没有语言C/C++!这是两种不同的语言。@Olaf ok。更正为C。我认为最必要的细节应该是#define(定义)GNU(源代码)up top:)
@DavidC.Rankin谢谢。编辑过。当然,我发现这篇文章的唯一原因是你的帖子让我偶然发现了一部分从未使用过的pthreads就在之前,我就去看了。谢谢。