0

Question is simple:

Example:

For (iterate based on amount of cores){
   Let worker = workers[I]
   Worker.postmessage
}

End of example .

Disclaimer: This example only shows what is expected of the end result and is in no means in what is considered "working condition" . Also note that the method used above does not return a worker for "workers[iterator]" instead just undefined.

Objective: Create working methods:

1: make array of unknown amount of workers(based on cores).

2: once that array is built, post a message to each worker and have a returned result(other than undefined).

Note: I do have a hypothesis of why it does not work:

1: web workers are created and are only accessable through the event that created them and its only acception is the onmessage "event" handler .

  • in defiance of my hypothesis there is such things that would say neigh to what is written above for example , like thread.js that allows for thread pooling and other procedures.

This is the main reason of why I ask , because I do know it is possible but would like a simple answer.

Thanks for your time .

2 Answers 2

1

Here is an example:

function createWorker (workerScript) {
    const blob = new Blob([`(${workerScript})(self)`], {type: 'application/javascript'});
    return new Worker(URL.createObjectURL(blob));
};

function workerCode (self) {
    self.onmessage = function (message) {
        postMessage(`Data from worker: ${message.data}`);
    };
};

// assuming that you will send only one message to the worker,
// and that the worker will produce only one message too.
function workerPromise (worker, message) {
    const promise = new Promise((resolve, reject) => {
        worker.onmessage = resolve;
    }).then(message => message.data);
    worker.postMessage(message);
    return promise;
}

(async () => {
    const workers = [];
    for (let i = 0; i < navigator.hardwareConcurrency; i++) {
        workers.push(createWorker(workerCode));
    }

    const results = await Promise.all(
        workers.map((w, index) => workerPromise(w, `worker ${index}`))
    );

    console.log(results);
})();
Sign up to request clarification or add additional context in comments.

2 Comments

how would I send multiple messages? Is there a way to just use your "createWorker" function and construct an array via for loop?. I just want a way to manage inumerable workers after their creation.
I also have no idea how your code is even supposed to work or proof that it even does , but understand that you probably wouldnt post it if it didnt. just would like a working example to I dont think ill mark this as an answer until a working example is displayed (for me and others that view for the sake of simplicity)
0

Start with the "Examples" section under: https://developer.mozilla.org/en-US/docs/Web/API/NavigatorConcurrentHardware/hardwareConcurrency

Modified example:

// in Main thread
const numberOfCPUCores = window.navigator.hardwareConcurrency;
const workerList = [];

const cpuWorkerMessageHandler = event => {
  // process message from a worker by accessing: event.data
}

for (let i = 0; i < numberOfCPUCores; i++) {
  const newWorker = new Worker('cpuworker.js');
  newWorker.addEventListener("message", cpuWorkerMessageHandler);
  workerList.push(newWorker);
}

// then, when done with all processing, terminate all workers
workerList.forEach(w => w.terminate());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.