设置与 C++ 的处理器关联性将在 Linux 上运行

发布于 2024-12-21 01:34:25 字数 270 浏览 3 评论 0原文

可能的重复:
CPU 亲和力

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

层林尽染 2024-12-28 01:34:25

在命令行中,您可以使用 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 ...
}

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 ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文