linux cpu亲和性设置

 1、设置进程的cpu亲和性程序如下,

#Using:g++ setCpuAffinity.c -o setCpuAffinity

#include<sys/types.h>
#include<sys/sysinfo.h>
#include<unistd.h>

//#define __USE_GNU
#include<sched.h>
#include<ctype.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>

int main(int argc, char* argv[])
{
        int num = sysconf(_SC_NPROCESSORS_CONF);
        int created_thread = 0;
        int myid, pid;
        int i;
        int j = 0;

        cpu_set_t mask;
        cpu_set_t get;

        if (argc < 3)
        {
                printf("usage : ./setAffinity pid num1,num2,..,numn \n");
                exit(1);
        }

        pid = atoi(argv[1]);
        CPU_ZERO(&mask);
        for (i = 2; i < argc; i++)
        {
                myid = atoi(argv[i]);
                CPU_SET(myid, &mask);
        }
        if (sched_setaffinity(pid, sizeof(mask), &mask) == -1)
        {
                printf("warning: could not set CPU affinity, continuing...\n");
        } else {
                printf("sched_setaffinity succeed !!!\n");

        }
}

 2、获取进程的CPU亲和性程序如下,

#Using:g++ getCpuAffinity.c -o getCpuAffinity

#include<sys/types.h>
#include<sys/sysinfo.h>
#include<unistd.h>

//#define __USE_GNU
#include<sched.h>
#include<ctype.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>

int main(int argc, char* argv[])
{
        int num = sysconf(_SC_NPROCESSORS_CONF);
        int pid;
        int i;

        cpu_set_t get;

        if (argc != 2)
        {
                printf("usage : ./setAffinity pid \n");
                exit(1);
        }

        pid = atoi(argv[1]);

        CPU_ZERO(&get);
        if (sched_getaffinity(pid, sizeof(get), &get) == -1)
        {
                printf("warning: cound not get cpu affinity, continuing...\n");
        }
        for (i = 0; i < num; i++)
        {
                if (CPU_ISSET(i, &get))
                {
                        printf("this process %d is running processor : %d\n", pid, i);
                }
        }
}

linux cpu亲和性设置,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。