Search code examples
c++multithreadingaffinitysetthreadaffinitymask

SethreadAffinityMask() correct usage?


I have 1500 threads..I want them to run on 12 processors... To do that I call SetThreadAffinityMask(GetCurrentThread(),1<<(threadnum%numprocessors)); where numprocessors=12. Is that correct usage of the mask? It needs to be scalable, that is if i want it to run on just 11 processors, then SetThreadAffinityMask(GetCurrentThread(),1<<(threadnum%numprocessors)); where numprocessors=11.


Solution

  • Syntactically SetThreadAffinityMask(GetCurrentThread(),1<<(GetThreadId()%numprocessors)) it's correct but it's not a good idea to use affinity just because you have a lot of threads and processors. it can interfere with the scheduler and degrade performance. You can use this for some threads to minimize cache misses. A cache miss occurs when a thread gets moved from one processor to another.