如何为数组中的Web worker创建/ postmessage

时间:2018-05-05 06:31:39

标签: javascript multithreading web-worker

问题很简单:

示例:

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

示例结束。

免责声明:此示例仅显示最终结果的预期结果,并不代表“工作条件”。另请注意,上面使用的方法不会返回“workers [iterator]”的worker,而只是返回undefined。

目标:创建工作方法:

1:制作一组未知数量的工人(基于核心)。

2:一旦构建了该数组,就向每个worker发布一条消息并返回一个结果(未定义)。

注意:我确实有一个假设,说明为什么它不起作用:

1:创建Web worker并且只能通过创建它们的事件访问它,并且它唯一的接受是onmessage“event”处理程序。

  • 无视我的假设,有些事情可以说明如上所述,例如thread.js允许线程池和其他程序。

这是我问的主要原因,因为我知道这是可能的,但想要一个简单的答案。

感谢您的时间。

2 个答案:

答案 0 :(得分:1)

以下是一个例子:

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);
})();

答案 1 :(得分:0)

https://developer.mozilla.org/en-US/docs/Web/API/NavigatorConcurrentHardware/hardwareConcurrency

下的“示例”部分开始

修改后的示例:

// 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());