For a CPU bound program which requires multi thread execution, we sometimes need certain number of processor cores to be used by our program and other cores to be left unassigned so that, other processes may utilize them.
Let's
make the idea more clear:
I develop
an exe application which performs long running calculations, such as
running heuristic algorithms. During the calculations, I want to reserve
some CPU resource for other processes so that my program will not "eat
up" all the CPU resource.
Processor
assignment can be achieved by setting processor affinity to threads:
C# Code:
We can specify the number of
cores that we want to be unassigned by setting the variable "unusedProcessorCount".
In the
code above, the function that fetches current thread id needs to be imported
from kernel32.dll.
As soon
as the function that thread executes is called, this function needs to
call SetProcessorAffinity by
passing its thread order so that the thread is assigned to the processor which
comes up next.
No comments:
Post a Comment