How to share singleton across multiple threads in nodejs

922 views Asked by At

I'm trying to have a singleton work across multiple threads in node/ts. But for some reason only main event loop has access to it. Is there any way I can have a singleton updated in the main loop, and have the changes reflected in a worker thread? Here's the code -

data_source.ts

class DataSource {
  private _data: any
  constructor() {
    this._data = []
  }

  set(data: any) {
    this._data.push(data)
  }

  get(id: any) {
    return this._data.find((d: any) => d.id === id)
  }
}

const instance = new DataSource();
Object.freeze(instance)
export default instance

index.ts

let workerpool = require('workerpool')
import DataSource from './data_source'
import { test } from './worker'

console.log(DataSource)


function main () {
  let pool = workerpool.pool()
  pool.exec(test, [])

  setInterval(() => {
    DataSource.set({id: 'asd'})
  }, 1000)
}

main()

worker.ts

import DataSource from './data_source'

export function test() {
  setInterval(() => {
    console.log(DataSource)
    console.log("test")
  }, 500)
}

As you can see, the main.ts executes a worker which "should" console log DataSource singleton every 0.5s, while main.ts adds new item to the DataSource every second.

This works if I emit the following line from worker - console.log(DataSource), a string "test" gets logged properly every 0.5s. But, when I try to console log DataSource in my worker thread, it gets logged properly for the first time only, and after that it seems that interval from main loop completely takes over the singleton and completely breaks the worker, and it stops logging anything.

I'm trying to use singleton as the schedule, main loop as scheduler, and worker as the executor (which checks the schedule every second).

Thank you!

0

There are 0 answers