Set the binding in std :: thread before executing

I want to map specific threads to some processors before executing, as we do, passing pthread_attr_tin pthread_create, but with objects std::thread. I 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);
}

Despite the fact that this code performs the task, it establishes proximity at an indefinite moment of execution of the thread, which leads to the fact that the processor can move the thread during execution to another processor.

If I set affinity as the first thing inside the stream code, passing zero

int rc = pthread_setaffinity_np(0, sizeof(cpu_set_t), &cpuset);

I get a segmentation error. If I pass pthread_self()instead of zero, I get EINVAL as the return.

int rc = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);

But changing the affinity of the thread after starting execution can also lead to movement of the thread.

, std:: thread?

EDIT: , .

+4

Source: https://habr.com/ru/post/1672236/


All Articles