sched_getcpu() 在 Linux 上可靠吗?

Is sched_getcpu() reliable on Linux?

我正在尝试调试 Linux 上 pthreads 的一些性能问题,我认为 sched_getcpu() 可能在骗我。它为每个线程报告一个常量 CPU,而分析实验似乎表明线程实际上在其生命周期内从一个内核迁移到另一个内核。

我想知道 sched_cpu() 是否只报告线程启动 运行 的第一个 CPU,而没有注意到线程迁移?有没有其他人注意到这一点,或者看到任何证据表明 sched_getcpu() 的 return 值可能会改变?如果它不可靠,是否还有其他方法可以跟踪当前 CPU(也许使用 CPUID?)?

http://man7.org/linux/man-pages/man2/getcpu.2.html 表示 sched_getcpu() 只是 getcpu() 的包装器。

http://man7.org/linux/man-pages/man2/getcpu.2.html 表明所提供的信息是准确的,因为不再使用旧的缓存选项:

The tcache argument is unused since Linux 2.6.24...it specified a pointer to a caller-allocated buffer in thread-local storage that was used to provide a caching mechanism for getcpu(). Use of the cache could speed getcpu() calls, at the cost that there was a very small chance that the returned information would be out of date. The caching mechanism was considered to cause problems when migrating threads between CPUs, and so the argument is now ignored.

因此,除非您使用的是 2.6.24 之前的内核,否则您似乎不太可能看到 old/cached 信息。

调用sched_getcpu有两个问题:

  1. 它只在执行调用时告诉你线程在哪里运行,
  2. 调用系统例程可能会导致线程迁移。

如果您使用的是 Intel 运行时,您可以设置 KMP_AFFINITY=verbose,因为它会在程序执行第一个并行部分时在 stderr 上提供相同的信息(格式不同)。