【问题标题】:setting processor affinity with C++ that will run on Linux [duplicate]使用将在 Linux 上运行的 C++ 设置处理器亲和性 [重复]
【发布时间】:2012-01-19 03:43:29
【问题描述】:

可能重复:
CPU Affinity

我在 Linux 上运行,我想编写一个 C++ 程序,该程序将设置 2 个特定处理器,我的 2 个应用程序将并行运行(即设置每个进程在不同的内核/CPU 上运行)。我想将处理器关联工具与 C++ 一起使用。请任何人帮助 C++ 代码。

【问题讨论】:

  • 您是否阅读过sched_setaffinitypthread_setaffinity_np 的手册页(以及从命令行执行的taskset)?如果是这样,您能描述一下您遇到的问题吗?

标签: c++ process processor affinity


【解决方案1】:

【讨论】:

    【解决方案2】:

    您可以在命令行中使用taskset(1),或者在您的代码中使用sched_setaffinity(2)

    例如

    #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,我想使用 C++ 自动运行,而不是通过命令行。我不太清楚如何使用 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);请问你有没有运行 C++ 代码,我可以用它来测试?
    • 非常感谢 Paul,这就是我要找的。​​span>
    猜你喜欢
    • 2013-03-19
    • 1970-01-01
    • 2018-02-19
    • 2014-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多