Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

201
Vistas
How to share singleton across multiple threads in nodejs

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!

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda