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.
I've already searched around various topics and on the internet and it seems C++ 11 API doesn't provide such low level feature.
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;
}
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.
The example in the linked reference even uses this to call pthread functions.
I do not know if it is a suitable approach in your case, but what I usually do is to call the affinity primitives from within the thread. E.g., I place a snippet of code similar to this one somewhere at the beginning of the threaded function:
const int err = pthread_setaffinity_np(pthread_self(),...);
The call to pthread_self()
will return the ID of the calling thread.
来源:https://stackoverflow.com/questions/16034448/obtaining-thread-core-affinity-in-c-11-through-pthreads