我正在尝试在 C++ 11 中使用 std::thread 时设置核心关联(线程 #1 在第一个核心上运行,线程 #2 在第二个核心上运行,...)。
我已经在各种主题和互联网上进行了搜索,似乎 C++ 11 API 不提供这种低级功能。
另一方面,pthreads 带有 pthread_setaffinity_np 如果我能得到我的 std::thread 的“pthread_t”值,这将很有用(我不知道这是人类合理的还是至少是合理的要求)。
我最终想要的示例程序是这样的:
#include <thread>
#include <pthread.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define CORE_NO 8
using namespace std;
void run(int id) {
cout << "Hi! I'm thread " << id << endl;
// thread function goes here
}
int main() {
cpu_set_t cpu_set;
CPU_ZERO(&cpu_set);
for(int i=0; i<CORE_NO; i++)
CPU_SET(i, &cpu_set);
thread t1(run, 1);
// obtaining pthread_t from t1
/*
pthread_t this_tid = foo(t1);
pthread_setaffinity_np(this_tid, sizeof(cpu_set_t), &cpu_set);
*/
t1.join();
return 0;
}
我真的不想改变我项目的整个架构(它必须提供这样的特性)。我现在大量使用 std::thread,但我也可以另外使用 pthread API,正如您在示例中看到的那样。
我有办法解决这个问题吗?
最佳答案
您可以使用 native_handle
获取线程的 native 句柄功能。
链接引用中的示例甚至使用它来调用 pthread 函数。
关于c++ - C++11中通过pthreads获取线程Core affinity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16034448/