I am trying to figure out how to set the thread affinity of std::thread or boost::thread using the win32 API. I want to use the SetThreadAffinityMask function to pin each thread to a particular core in my machine.
I used the thread native_handle member function to obtain the thread handle that is provided to the SetThreadAffinityMask function. However, doing this results in the SetThreadAffinityMask function returning 0, indicating a failure to set thread affinity.
unsigned numCores = std::thread::hardware_concurrency();
std::vector<std::thread> threads(numCores);
for (int i = 0; i < numCores; i++)
{
threads.push_back(std::thread(workLoad, i));
cout << "Original Thread Affinity Mask: " << SetThreadAffinityMask(threads[i].native_handle() , 1 << i) << endl;
}
for (thread& t : threads)
{
if (t.joinable())
t.join();
}
Original Thread Affinity Mask: 0
Original Thread Affinity Mask: 0
Original Thread Affinity Mask: 0
Original Thread Affinity Mask: 0
Original Thread Affinity Mask: 0
Original Thread Affinity Mask: 0
Original Thread Affinity Mask: 0
...etc