I want to map certain threads to certain processors before the execution, in a way we do by passing pthread_attr_t
in pthread_create
, but with std::thread
objects. I have tried the following:
std::vector<std::thread> threads;
for (int i = 0; i<num_threads; i++) {
threads.push_back(std::thread(&some_struct::run, some_structs_vector.at(i)));
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(i, &cpuset);
int rc = pthread_setaffinity_np(threads.at(i).native_handle(), sizeof(cpu_set_t), &cpuset);
assert(rc == 0);
}
Though this code does the job, it sets the affinity in an unspecified moment of the thread execution, leading the processor to potentially have to move the thread during execution to another processor.
If i set affinity as the first thing inside the thread code, by passing zero
int rc = pthread_setaffinity_np(0, sizeof(cpu_set_t), &cpuset);
i get segmentation fault. If i pass pthread_self()
instead of zero i get EINVAL as a return.
int rc = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
But changing the affinity of the thread, after the execution has started, can also potentially cause the thread to be moved.
So how can i set the thread affinity, before execution has started, with modern std::thread objects?
EDIT: I don't care about priority, just mapping to certain cores.