Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!