Search code examples
c++windowssetthreadaffinitymask

SetThreadAffinityMask has no effect


I want a test program only run on cpu1 ,so i write the code like that

#include <iostream>
#include <windows.h>

    int main(){
        ::SetThreadAffinityMask(::GetCurrentProcess(),1);
        while(1)
          ;
       return 0;
    }

but when I open the task manager, I find CPU1 is not full used, and the percent of it's usage is always changing.Why?CPU1 should be 100 percent usage? sorry to my english.


Solution

  • SetThreadAffinityMask sets the affinity of a THREAD not of the whole process. If you check the return value you should see that SetThreadAffinityMask is failing. To get the current thread use GetCurrentThread() not GetCurrentProcess().

    i.e. change your code to

    SetThreadAffinityMask(GetCurrentThread(),1) 
    

    If you want to set the affinity of the whole process use

    SetProcessAffinityMask(GetCurrentProcess(),1)