5

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.

k_kaz
  • 596
  • 1
  • 9
  • 20
  • Possible duplicate of [Setting thread priority in Linux with Boost](http://stackoverflow.com/questions/1479945/setting-thread-priority-in-linux-with-boost) – Tatsuyuki Ishi Mar 14 '17 at 11:28
  • This post suggests that i change the affinity of the ''creator'' thread every time it spawns a new thread, hoping that the newly created will inherit it's creator's configuration... I was hoping for something more elegant. – k_kaz Mar 14 '17 at 11:32
  • @TatsuyukiIshi Rather not. The question you linked deals with `boost::thread` while this question deals with `std::thread`, which are, although similar, not the same, – Ben Steffan Mar 14 '17 at 14:20
  • 1
    @BenSteffan at the bottom (comments) of the answer, it was stated that it also applies to `std`. – Tatsuyuki Ishi Mar 14 '17 at 14:21
  • @TatsuyukiIshi Ah, I overlooked that. Still, only that that answer works for `std::thread`, too, doesn't mean that there is no better solution for `std::thread`. – Ben Steffan Mar 14 '17 at 14:24
  • 1
    Eli Bendersky has an article "C++11 threads, affinity and hyperthreading": https://eli.thegreenplace.net/2016/c11-threads-affinity-and-hyperthreading/ – Zingam Sep 02 '18 at 08:15

0 Answers0