Search code examples
javascriptnode.jsforkcpuspawn

Node.js child process fork: CPU affinity


I am wanting to use the child_process.fork function in Node.js, to spawn a new process. This example also works with the spawn function.

To ensure that these child processes are taking advantage of all the cores on the machine evenly, I want to set their CPU affinity, thus forcing them to migrate to the desired cores.

I know how to do this in C, and in the terminal, but how would I do this in Node.js?


Solution

  • I'll preface this by saying that setting the processor affinity of your your process is probably a bad idea. Every node process has a number of threads (the main V8 thread that your JS runs in plus libuv threads for doing I/O and other native stuff), and limiting the node process to a single core will necessarily slow things down.

    Doing nothing and letting the OS scheduler deal with your forked processes and their threads is likely to yield better performance.

    Of course, the only way to really know is to benchmark the system under load. Test different levels of load (light, medium, high) and see what performs better.


    I can think of two ways of setting process affinity:

    1. Ugly: Use exec() to run taskset to set your process' affinity. (Use process.pid for the current process, or the pid property of the ChildProcess returned from fork().)

    2. Way better: Write a native binding to the platform API. (How you'd do it in C.) This module appears to do so; is old so it may or may not work.