通过pthreads获取C++ 11中的线程核心关联

Rob*_*013 8 c++ multicore pthreads affinity c++11

我正在尝试设置核心亲和力(线程#1进入第一个核心,线程#2进入第二个核心,......),同时在C++ 11中使用std :: thread.

我已经在各种主题和互联网上搜索过,似乎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;
}
Run Code Online (Sandbox Code Playgroud)

我真的不想改变我的项目的整体架构(必须提供这样的特性).我现在大量使用std :: thread,但我也可以使用pthread API,正如您在示例中看到的那样.

我有办法解决这个问题吗?

Som*_*ude 10

您可以使用该native_handle函数获取该线程的本机句柄.

链接引用中的示例甚至使用它来调用pthread函数.


blu*_*rni 7

我不知道在你的情况下它是否是一种合适的方法,但我通常做的是从线程中调用亲和性原语.例如,我在线程函数的开头放置了一段与此类似的代码片段:

const int err = pthread_setaffinity_np(pthread_self(),...);
Run Code Online (Sandbox Code Playgroud)

调用pthread_self()将返回调用线程的ID.