2
votes

I use C++11 threading and need to set the affinity of a thread to a given processor core (windows' scheduler is not delegating to cores intelligently and I want control over what thread goes to what core).

For windows, there is

SetThreadAffinityMask(GetCurrentThread(), affinity);

What would a single cross-platform function look like that would work on windows, linux and OSX, with all the permutations of underlying threading libraries (windows threads, pthreads, etc.)?

1
You can get the native handle from std but from there you will need platform specific implementations - didiz
That is precisely correct - hence why I asked this question... - ibell

1 Answers

1
votes

If part of C++, I suspect it would look something like the pair of member function:

std::error_code std::thread::hardware_affinity(const std::vector<bool>&);

and free function:

std::error_code std::this_thread::hardware_affinity(const std::vector<bool>&);

on the assumption that we're talking about roughly the same sort of resources that std::thread::hardware_concurrency() counts, and that std::thread implementations must already take care of "all the permutations of underlying threading libraries".

Building one yourself, or using a utility library (I can't name an existing one right now) it would probably look like:

thread_utils::hardware_affinity(std::thread::native_handle_type, const std::vector<bool>&)

but it would have to support all the permutations internally. That's not hugely hard (many applications have done it out of necessity anyway), but it's more work than a Stack Overflow answer can hold. ^_^

One annoying limitation with this approach is that although there is the member function std::thread::native_handle(), there's no std::this_thread::native_handle() method. It's basically pending a write-up and a good use case to be standardised.