setting processor affinity with C++ that will run on Linux [duplicate]

孤街醉人 提交于 2019-11-30 23:27:05

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 ...
}
Basile Starynkevitch
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!