如何从 C 在 Linux 中使用 sched_getaffinity 和 sched_setaffinity?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10490756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:13:08  来源:igfitidea点击:

How to use sched_getaffinity and sched_setaffinity in Linux from C?

clinuxprocessscheduleaffinity

提问by Basmah

I am trying to:

我在尝试着:

  • Run 16 copies concurrently with processor pinning (2 copies per core)

  • Run 8 copies concurrently with processor pinning (2 copies per core) and flipping processor core to the furthest core after certain function say function 1 finishes.

  • 与处理器固定同时运行 16 个副本(每个内核 2 个副本)

  • 与处理器固定同时运行 8 个副本(每个内核 2 个副本),并在某些功能说功能 1 完成后将处理器内核翻转到最远的内核。

The problem I am facing is how to select the farthest processor.

我面临的问题是如何选择最远的处理器。

Some friends suggested to use sched_getaffinity and sched_setaffinity but I count not find any good examples.

有些朋友建议使用 sched_getaffinity 和 sched_setaffinity 但我数了数没有找到任何好的例子。

采纳答案by Pete Fordham

To use sched_setaffinity to make the current process run on core 7 you do this:

要使用 sched_setaffinity 使当前进程在核心 7 上运行,您可以执行以下操作:

cpu_set_t my_set;        /* Define your cpu_set bit mask. */
CPU_ZERO(&my_set);       /* Initialize it all to 0, i.e. no CPUs selected. */
CPU_SET(7, &my_set);     /* set the bit that represents core 7. */
sched_setaffinity(0, sizeof(cpu_set_t), &my_set); /* Set affinity of tihs process to */
                                                  /* the defined mask, i.e. only 7. */

See http://linux.die.net/man/2/sched_setaffinity& http://www.gnu.org/software/libc/manual/html_node/CPU-Affinity.htmlfor more info.

有关更多信息,请参阅http://linux.die.net/man/2/sched_setaffinity& http://www.gnu.org/software/libc/manual/html_node/CPU-Affinity.html

回答by death by snu-snu

Don't use CPU_SETSIZE as cpusetsize parameter for sched_[set|get]affinity. The names are misleading but this is wrong. The makro CPU_SETSIZE is (quoting man 3 cpu_set) "a value one greater than the maximum CPU number that can be stored in cpu_set_t." You have to use

不要使用 CPU_SETSIZE 作为 sched_[set|get]affinity 的 cpusetsize 参数。这些名称具有误导性,但这是错误的。makro CPU_SETSIZE 是(引用 man 3 cpu_set)“比可以存储在 cpu_set_t 中的最大 CPU 数量大一的值。” 你必须使用

sched_setaffinity(0, sizeof(cpu_set_t), &my_set);

instead.

反而。