为什么 openmp 不放置基于手动 NUMA 绑定的线程?

Why doesn't openmp place threads based on manual NUMA bind?

我正在构建一个绑定到给定套接字并接受 lambda 的 numa 感知处理器。这是我所做的:

#include <numa.h>
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <thread>
#include <vector>

using namespace std;

unsigned nodes = numa_num_configured_nodes();
unsigned cores = numa_num_configured_cpus();
unsigned cores_per_node = cores / nodes;

int main(int argc, char* argv[]) {
    putenv("OMP_PLACES=sockets(1)");
    cout << numa_available() << endl;  // returns 0
    numa_set_interleave_mask(numa_all_nodes_ptr);
    int size = 200000000;
    for (auto i = 0; i < nodes; ++i) {
        auto t = thread([&]() {
            // binding to given socket
            numa_bind(numa_parse_nodestring(to_string(i).c_str()));
            vector<int> v(size, 0);
            cout << "node #" << i << ": on CPU " << sched_getcpu() << endl;
#pragma omp parallel for num_threads(cores_per_node) proc_bind(master)
            for (auto i = 0; i < 200000000; ++i) {
                for (auto j = 0; j < 10; ++j) {
                    v[i]++;
                    v[i] *= v[i];
                    v[i] *= v[i];
                }
            }
        });
        t.join();
    }
}

但是,所有线程都在套接字 0 上 运行。似乎 numa_bind 没有将当前线程绑定到给定的套接字。第二个 numa 处理器 -- Numac 1 输出 node #1: on CPU 0,它应该在 CPU 1 上。那么出了什么问题?

这完全符合我的预期:

#include <cassert>
#include <iostream>
#include <numa.h>
#include <omp.h>
#include <sched.h>

int main() {
   assert (numa_available() != -1);

   auto nodes = numa_num_configured_nodes();
   auto cores = numa_num_configured_cpus();
   auto cores_per_node = cores / nodes;

   omp_set_nested(1);

   #pragma omp parallel num_threads(nodes)
   {
      auto outer_thread_id = omp_get_thread_num();
      numa_run_on_node(outer_thread_id);

      #pragma omp parallel num_threads(cores_per_node)
      {
         auto inner_thread_id = omp_get_thread_num();

         #pragma omp critical
         std::cout
            << "Thread " << outer_thread_id << ":" << inner_thread_id
            << " core: " << sched_getcpu() << std::endl;

         assert(outer_thread_id == numa_node_of_cpu(sched_getcpu()));
      }
   }
}

程序首先在我的 dual-socket 服务器上创建 2 个(外部)线程。然后,它将它们绑定到不同的套接字(NUMA 节点)。最后,它将每个线程拆分为 20 个(内部)线程,因为每个 CPU 都有 10 个物理内核并启用了超线程。

所有内部线程都运行在与其父线程相同的套接字上。对于外线程 0,这是在核心 0-9 和 20-29 上,对于外线程 1,在核心 10-19 和 30-39 上。(sched_getcpu() 返回了我的 0-39 范围内的虚拟核心数例。)

请注意,没有 C++11 线程,只有纯 OpenMP。