3

Possible Duplicate:
CPU Affinity

I'm running on Linux and I want to write a C++ program that will set 2 specific processors that my 2 applications that will run in parallel (i.e. setting each process to run on a different core/CPU). I want to use processor affinity tool with C++. Please can anyone help with C++ code.

Community
  • 1
  • 1
Ifeanyi
  • 41
  • 1
  • 1
  • 4
  • 2
    Have you read the manpages for `sched_setaffinity` and `pthread_setaffinity_np` (and also `taskset` to do it from the command line)? If so, could you describe the problems you're having? – Mike Seymour Dec 13 '11 at 08:42

2 Answers2

10

From the command line you can use taskset(1), or from within your code you can use sched_setaffinity(2).

E.g.

#ifdef __linux__    // Linux only
#include <sched.h>  // sched_setaffinity
#endif

int main(int argc, char *argv[])
{
#ifdef __linux__
    int cpuAffinity = argc > 1 ? atoi(argv[1]) : -1;

    if (cpuAffinity > -1)
    {
        cpu_set_t mask;
        int status;

        CPU_ZERO(&mask);
        CPU_SET(cpuAffinity, &mask);
        status = sched_setaffinity(0, sizeof(mask), &mask);
        if (status != 0)
        {
            perror("sched_setaffinity");
        }
    }
#endif

    // ... your program ...
}
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • Thanks Paul, I want to auto run with C++ instead of going through command line. I am not too sure of how to use int sched_setaffinity(pid_t pid, size_t cpusetsize, cpu_set_t *mask); int sched_getaffinity(pid_t pid, size_t cpusetsize, cpu_set_t *mask); please do you have run C++ code, that I can test with? – Ifeanyi Dec 13 '11 at 08:54
0

You need to call sched_setaffinity or pthread_setaffinity_np

See also this question

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547