You can do this with two calls to SetThreadAffinityMask . This function returns the original bond mask for the processed stream descriptor.
So ... make one call using a mask that establishes proximity to one CPU, and then make a second call to restore the original mask.
Here is the complete C / C ++ source code, including error checking:
DWORD GetThreadAffinityMask(HANDLE thread) { DWORD mask = 1; DWORD old = 0; // try every CPU one by one until one works or none are left while(mask) { old = SetThreadAffinityMask(thread, mask); if(old) { // this one worked SetThreadAffinityMask(thread, old); // restore original return old; } else { if(GetLastError() != ERROR_INVALID_PARAMETER) return 0; // fatal error, might as well throw an exception } mask <<= 1; } return 0; }
This code checks one processor at a time until the proximity property is set (in this case, we now know the original mask!) Or until the initial 1 is shifted from DWORD . If a processor that is unavailable is requested, the function does not work with ERROR_INVALID_PARAMETER , and we just try the following. Usually the first processor will work, so it is quite efficient.
If the function fails with anything other than ERROR_INVALID_PARAMETER , this means that we either do not have sufficient access rights to the descriptor, or the system has some real problems because it cannot fulfill our request. Therefore, in this case, it makes no sense to continue.
source share