通过pthread在C ++ 11中获得线程核心相似性 [英] Obtaining thread Core affinity in C++ 11 through pthreads

查看:79
本文介绍了通过pthread在C ++ 11中获得线程核心相似性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to set core affinity (Thread #1 goes on first core, Thread #2 goes on second core, ...) while using std::thread in C++ 11.

我已经在互联网上搜索了各种主题,似乎C ++ 11 API没有提供这种低级功能.

I've already searched around various topics and on the internet and it seems C++ 11 API doesn't provide such low level feature.

另一方面,pthread附带了 pthread_setaffinity_np ,如果我可以获取std :: thread的"pthread_t"值,这将很有用(我不知道这是否是人类合理的,或者至少是合法的要求.

On the other hand, pthreads come with pthread_setaffinity_np which would be useful if I could get the "pthread_t" value of my std::thread (I don't know if this is human reasonable or at least legitimate asking for it).

我最后想要的示例程序是:

An example program of what I'd want to have in the end is this:

#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,如您在示例中所看到的.

I'd really prefer not to change the whole architecture of my project (which must provide such characteristic). I've now a massive use of std::thread but I can use pthread API in addition as well, as you have seen in the example.

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

Is there a way for me to solve this problem?

推荐答案

您可以使用

You can get the native handle for the thread with the native_handle function.

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

The example in the linked reference even uses this to call pthread functions.

这篇关于通过pthread在C ++ 11中获得线程核心相似性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆