SethreadAffinityMask() correct usage?

530 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

that's correct.

but for performance and efficiency reasons, i'am suggesting that you change your threading model somehow that the thread count is equal to number of CPU execution core, then those threads work on your 1500 tasks/work item which distributed by your "task manager".

if you don't want to create your own "task manager", you can use windows ThreadPool API, which you assign a task to a "thread pool" managed by O/S