3

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

Joe Schmoe
  • 33
  • 1
  • 6

1 Answers1

3

Your problem is the intial setup of threads to contain numCores default-initialized entries. Your new (read: real) threads are pushed on the vector afterward, but you never index to them when setting affinity. Instead you index using i, which just hits the objects in the vector that aren't really running threads, prior to your real threads.

A corrected version that's actually run-worthy appears below:

#include <iostream>
#include <vector>
#include <thread>
#include <chrono>

#include <windows.h>

void proc(void)
{
    using namespace std::chrono_literals;
    std::this_thread::sleep_for(5s);
}

int main()
{
    std::vector<std::thread> threads;
    for (unsigned int i = 0; i < std::thread::hardware_concurrency(); ++i)
    {
        threads.emplace_back(proc);
        DWORD_PTR dw = SetThreadAffinityMask(threads.back().native_handle(), DWORD_PTR(1) << i);
        if (dw == 0)
        {
            DWORD dwErr = GetLastError();
            std::cerr << "SetThreadAffinityMask failed, GLE=" << dwErr << '\n';
        }
    }

    for (auto& t : threads)
        t.join();
}
WhozCraig
  • 65,258
  • 11
  • 75
  • 141