c++ - C++11中通过pthreads获取线程Core affinity

标签 c++ c++11 pthreads multicore affinity

我正在尝试在 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/

相关文章:

c++ - 从优先级队列中获取 unique_ptr

c++ - 如果在构造中使用,则自动创建成员

c++ - 模板类中的命名空间特化

c++ - 无法将枚举值传递给递归模板 (C++)

c - pthread_join 死锁的简单示例

c++ - 迁移到 64 位时,内存使用量可能会增长多少?

c++ - 确定代码是否在特定线程中运行

c++ - 来自具有浮点类型的模板实例化的移位编译错误

linux - Pthread互斥锁由不同线程解锁

c++ - C++11 theads 的最基本并行化失败