c++windowsmultithreadingc++11winapi

Using std::thread and native_handle() to set thread affinity mask


Is this the right way to create a thread and set the affinity using std::thread ?

std::thread myThread(threadFunction);

HANDLE threadHandle = myThread.native_handle();

SetThreadAffinityMask(threadHandle, 1);

Solution

  • Yes, that is correct.

    In case you want to set it back to the original at some point, SetThreadAffinityMask also returns the old mask:

    HANDLE threadHandle = myThread.native_handle();
    
    DWORD_PTR new_mask = 1;
    DWORD_PTR old_mask = SetThreadAffinityMask(threadHandle, new_mask);
    

    In case old_mask is zero, setting the affinity failed.