Skip to content

Can I require stuff and initialize services and objects outside the function of a function worker? #368

Open
@andrec93p

Description

@andrec93p

Hello and thank you for this amazing package. I've being using it for years at this point, and it allowed for really cool things.

I have this long-running project that uses this package, and I recently updated it from version 0.8 to 1.6, doing every adjustment needed to the code. I must say I really like how the new version works, much better and cleaner than v0. I have a question that I can't find the answer to from the code and the documentation though.

Suppose I have a pool of workers, with each worker using its own instance of one or more services, like the API client for a specific library (specifically, the Firebase and APN clients to send push notifications to mobile devices). I want to initialize the service when I spawn every worker in the pool for the first time, but I want the services to be already initialized with the same instance from before when a worker is reused. Of course, whenever a worker dies and a new one spawns, the new one will have to reinitialize them and get new instances. No problem about it.

So we're talking about something close to this.

const Worker = require("threads/worker");
const someOtherLibrary = require('some-other-library');
const someConfiguration = require('./config/some-configuration');

const service1 = someOtherLibrary.initializeService1(someConfiguration);
const service2 = someOtherLibrary.initializeService2(someConfiguration);

Worker.expose(async function() {
    service1.doSomething(someConfiguration);
    service2.doSomethingElse(someConfiguration);
    ...
});

Would this work? Is it right in your vision for this package? If not, how can I correct it?

Thank you.

EDIT: I already made a few attempts and this seems to work, but I wanted to know your own thoughts about it.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions