有人可以解释 webworker-thread 示例吗? [英] Can someone explain the webworker-thread example?

查看:24
本文介绍了有人可以解释 webworker-thread 示例吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var Worker = require('webworker-threads').Worker;
require('http').createServer(function (req,res) {
  var fibo = new Worker(function() {
    function fibo (n) {
      return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1;
    }

    // which onmessage does this this refer to?
    onmessage = function (event) {  //reference 1
      postMessage(fibo(event.data));
    }
  });
  fibo.onmessage = function (event) { //reference 2
    res.end('fib(40) = ' + event.data);
  };
  fibo.postMessage(40);
}).listen(port);

这是作为 webworker 类示例的代码.

This is the code found as an example for the webworker class.

我正在查看 API,但似乎不明白上述代码中的引用 1 指的是什么.为什么 postMessage(40) 命中内部 onmessage 函数而不是 fibo.onmessage 函数?

I was looking at the API and doen't seem to understand what reference 1 in the above code is referring to. Why does the postMessage(40) hit the inner onmessage function and not the fibo.onmessage function?

推荐答案

这里要注意的要点是 onmessage() 和 postmessage() 用作主线程和工作线程之间的消息承载.这最初可能会令人困惑.所以流程是这样的

The main point to note here is that the onmessage() and postmessage() is used as message bearers between both the main thread and the worker thread. This can be confusing initially. So the flow goes like this

  1. 创建一个工作线程.

  1. Create a worker thread .

var fibo= new Worker...

这将在节点中生成另一个 JavaScript 线程.它可以在后台并行运行并使用所有可用的 CPU 内核.否则在 node 中由于其单线程模型,不可能利用多个 CPU 内核(因此工作线程是处理 node 中 CPU 绑定任务的好方法)

This will spawn another JavaScript thread in the node. It can run in parallel in the background and use all the available CPU cores. Otherwise in node due to its single threaded model, taking advantage of multiple CPU cores is not possible (hence worker threads is a good approach for handling CPU-bound tasks in node)

  1. 在工作线程中我们定义a) 如何处理它收到的请求/工作 - onmessage() 完成这项工作.它会侦听任何传入的工作请求并对其采取行动.

onmessage= function (event) {//参考1postMessage(fibo(event.data));}

b) 工作完成后如何与主线程通信-postMessage 完成这项工作.

b) how to communicate back to the main thread once work is done- postMessage does this job.

postMessage(fibo(event.data));

  1. 在主线程中:-一种.调用工作线程并给它一个任务来执行 - 即.使用 postmessage(现在你已经跳舞了)

  1. In the main thread :- a. Call the worker thread and give it a task to execute -ie. using postmessage (By now you got the dance)

fibo.postMessage(40);

B.定义有关工作线程完成其工作并响应后要采取的操作的侦听器.IE.使用 onmessage.

b. Define listener regarding the action to take once the worker thread finishes it job and responds back. ie. using onmessage.

fibo.onmessage = function (event) { //reference 2
res.end('fib(40) = ' + event.data);

};

这篇关于有人可以解释 webworker-thread 示例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆