Home » Javascript » How to initialize a child process with passed in functions in Node.js

How to initialize a child process with passed in functions in Node.js

Posted by: admin August 19, 2018 Leave a comment



I’m building a general purpose game playing A.I. framework/library that uses the Monte Carlo Tree Search algorithm. The idea is quite simple, the framework provides the skeleton of the algorithm, the four main steps: Selection, Expansion, Simulation and Backpropagation. All the user needs to do is plug in four simple(ish) game related functions of his making:

  1. a function that takes in a game state and returns all possible legal moves to be played
  2. a function that takes in a game state and an action and returns a new game state after applying the action
  3. a function that takes in a game state and determines if the game is over and returns a boolean and
  4. a function that takes in a state and a player ID and returns a value based on wether the player has won, lost or the game is a draw. With that, the algorithm has all it needs to run and select a move to make.

What I’d like to do

I would love to make use of parallel programming to increase the strength of the algorithm and reduce the time it needs to run each game turn. The problem I’m running into is that, when using Child Processes in NodeJS, you can’t pass functions to the child process and my framework is entirely built on using functions passed by the user.

Possible solution

I have looked at this answer but I am not sure this would be the correct implementation for my needs. I don’t need to be continually passing functions through messages to the child process, I just need to initialize it with functions that are passed in by my framework’s user, when it initializes the framework.

I thought about one way to do it, but it seems so inelegant, on top of probably not being the most secure, that I find myself searching for other solutions. I could, when the user initializes the framework and passes his four functions to it, get a script to write those functions to a new js file (let’s call it my-funcs.js) that would look something like:

const func1 = {... function implementation...}
const func2 = {... function implementation...}
const func3 = {... function implementation...}
const func4 = {... function implementation...}

module.exports = {func1, func2, func3, func4}

Then, in the child process worker file, I guess I would have to find a way to lazy load require my-funcs.js. Or maybe I wouldn’t, I guess it depends how and when Node.js loads the worker file into memory. This all seems very convoluted.

Can you describe other ways to get the result I want?