I am running a node js application. When it starts I create one worker per core. I need to create some kind of global variable shared between every worker I created. Is there any way to do this?
2 Answers
For a small set of variables you can spawn workers with custom environments. For example:
// On the master when creating the process:
cluster.fork({ GLOBAL_VAR_A: 12345 });
// On workers:
var globalA = parseInt(process.env.NODE_GLOBAL_VAR_A, 10);
I've put a parseInt in here to highlight that environment variables are strings. This should only be used for a few variables though, since it obviously scales badly.
There are two important alternatives though
- Configuration Files: Much of the time, data you want to share is really configuration. Configuration can be simply stored in files, and all workers will read in the same data.
- Databases: The other is shared state via database. For example, redis pubsub allows you to maintain synchronised variables between workers, if you really need it.
As mentioned in alex's answer, native cluster IPC is an option too, but is really for communicating between master and workers. You don't want to have your master process doing too much to avoid possible bugs that throw uncaught exceptions. It may also be worth looking at zeromq etc.