Setting ProcessorAffinity and the TPL

2019-05-22 12:25发布

If I set my processor affinity for my process like so:

var me = Process.GetCurrentProcess();
me.ProcessorAffinity = (IntPtr) processorAffinityMask;

..., will the TPL honor that for all of its work? That is, are there any got-ya's with the default scheduler that would push work to a processor not allowed by my given mask? Is there a test that will prove this?

1条回答
地球回转人心会变
2楼-- · 2019-05-22 12:48

Yes the TPL will honor the affinity mask that you specify.

The only way it could not honor it is to explicitly go and change the affinity, and it does not do that.

While it would be highly unfeasible to create a test that would exercise every possible code path in TPL, you can certainly setup a test that would benefit from many available cores, set the affinity mask to 1 CPU, and observe through Task Manager that the affinity never changes and CPU utilization is never more than 1/N where N is the # of cores present.

You could also expand that test to have an affinity of M cores, and observe that CPU utilization <= M/N. You can also directly observe that the affinity does not change in Task Manager.

A suitable test would be one that requires significant time per iteration and offers many independent units of work, e.g. calculate the first prime > N where N is large and use Parallel.Foreach on an array of target primes. The array size should be significantly greater than the number of cores present.

On a side note, it is seldom a good idea to explicitly set the CPU affinity. Curious what your use case is.

查看更多
登录 后发表回答