1
votes

I am using cpuset from the command line (i.e. http://man7.org/linux/man-pages/man7/cpuset.7.html) to run a C/C++ program.

I wonder whether the C/C++ is able to retrieve the cpuset it is running on top of.

I read http://man7.org/linux/man-pages/man3/CPU_SET.3.html but I don't see any macro there to be able to achieve what I want.

The main reason I would like to retrieve the cpuset inside the program is to fill cpu_set_t* so that I can pass it to pthread_attr_setaffinity_np().

Thanks in advance.

2

2 Answers

1
votes
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
if (0 == sched_getaffinity(getpid(), sizeof(cpu_set_t), &cpuset)) {
    const long nCores = sysconf( _SC_NPROCESSORS_ONLN );
    for (long i = 0; i < nCores; i++) {
        if (CPU_ISSET(i, &cpuset)) {
            std::cout << "core # " << i << " is in cpuset" << std::endl;
        }
    }
}
else {
    std::cerr << "sched_getaffinity() failed: " << strerror(errno) << std::endl;
}
0
votes

U can work on CPU set as

    #define _GNU_SOURCE
    #include <sched.h>


    cpu_set_t my_set;
    CPU_ZERO(&my_set);
    CPU_SET(1, &my_set); // here 1 is the cpu 1 similarly u can set more
    CPU_SET(2, &my_set); // here 2 is the cpu 2 similarly u can set more
    pthread_setaffinity_np(pthread_self(), sizeof (cpu_set_t), &my_set);