So a computer might have a single processor, and this single processor might only have a single core. On a system like this threading can be achieved by way of time slicing, that is switching between instructions very fast giving the illusion that they are being executed in parallel.
On modern computers a computer might have more than one processor, and each processor might have more than one core. On a system like this time slicing could be done, however true parallel exaction of instructions can be achieved as well.
As I understand it, threads are part of what makes up a process that runs on an operating system. There can be one or more threads per process, and then more than one process running on the operating system of a computer. All the threads might be running on the same core by way of time slicing, or on separate cores in parallel.
There are two built in modules that are of interest which are:
The child-process module is what can be used to run a command on the operating system, it can be some other software tool written in another language, or another script launched with node.js, in ether case it will run as it’s own independent process separate from the main script that launched it.
This post however is on the cluster module that can be used to fork a single script into more than one process.
For a basic usage example I made a script that launches a fork for every core on the system that it runs, and each fork just counts to ten, and kills itself. Another useful core module in node.js is the os module that gives me information about the system that the node.js script is running on.
So I made a basic.js file in a test folder that looks like this:
As you can see I am still using setInterval to call a function more than once, but it is being used in it’s own separate process launched with cluster.fork, so it is not the same thing as just emulating threading which would be the case if I where using setInterval by itself.
In the future I might expand on this post, and others like it. There is a lot more to write about with clustering alone in node.js.