Turn off multithreading or limit core usage in F#? – Education Career Blog

Is there a way to turn off multithreading or limit the number of cores used by an F# app? I’m aware this wouldn’t be done in a production environment but I’m curious if I have to actually install the application on a single cored system in order to see how it would perform.

,

You can simply set this at the beginning of your application by setting the value for the current process’s ProcessorAffinity:

System.Diagnostics.Process.GetCurrentProcess().ProcessorAffinity <- nativeint 1

This would effectively limit the cores used for the process to the first CPU on the system.

,

Tweaking the register or using Process.ProcessorAffinty directly modify the windows process scheduler. This is a bad practice as it is platform dependent and additionally could produce program behaviors which are difficult to pin down the cause of. If possible, it’s much better to do this via .NET itself without using PInvoke wrappers like System.Diagnostics.Process.

If you only want your application to use a single thread I suggest setting the garbage collector to be non-concurrent by adding the following to your app.config:

<configuration>
   <runtime>
       <gcConcurrent enabled="false"/>
   </runtime>
</configuration>

For more information, see my post on this topic here.

If you want to set explicit limits on the upper and lower bounds on the number of threads it is best to use the ThreadPool object. By using the SetMaxThreads and SetMinThreads you can safely enforce these limits without touching the windows system scheduler.

The only significant limitation to using ThreadPool is that in using this method you cannot set the minimum number of threads to be less than the number of processors in your computer.

,

You can set the process affinity through tweaking the registry, which will limit your application as desired.

Leave a Comment