Threads in Node 10.5.0: a practical intro
发布日期:2021-06-24 18:23:25 浏览次数:2 分类:技术文章

本文共 2523 字,大约阅读时间需要 8 分钟。

A few days ago, version 10.5.0 of Node.js was released and one of the main features it contained was the addition of initial (and experimental) thread support.

This is interesting, specially coming from a language that’s always pride itself of not needed threads thanks to it’s fantastic async I/O. So why would we need threads in Node?

The quick and simple answer is: to have it excel in the only area where Node has suffered in the past: dealing with heavy CPU intensive computations. This is mainly why Node.js is not strong in areas such as AI, Machine Learning, Data Science and similar. There are a lot of efforts in progress to solve that, but we’re still not as performant as when deploying microservices for instance.

So I’m going to try and simplify the technical documentation provided by the initial PR and the official docs into a more practical and simple set of examples. Hopefully that’ll be enough to get you started.

So how do we use the new Threads module?

To start with, you’ll be requiring the module called “worker_threads”.

Note that this will only work if you use the --experimental-worker flag when executing the script, otherwise the module will not be found.

Notice how the flag refers to workers and not threads, this is how they’re going to be referenced throughout the documentation: worker threads or simply workers.

If you’ve used multi-processing in the past, you’ll see a lot of similarities with this approach, but if you haven’t, don’t worry, I’ll explain as much as I can.

What can you do with them?

Worker threads are meant, like I mentioned before, for CPU intensive tasks, using them for I/O would be a waste of resources, since according to the official documentation, the internal mechanism provided by Node to handle async I/O is much more efficient than using a worker thread for that, so… don’t bother.

Let’s start with a simple example of how you would go about creating a worker and using it.

Example 1:

const { Worker, isMainThread,  workerData } = require('worker_threads');let currentVal = 0;let intervals = [100,1000, 500]function counter(id, i){    console.log("[", id, "]", i)    return i;}if(isMainThread) {    console.log("this is the main thread")    for(let i = 0; i < 2; i++) {        let w = new Worker(__filename, {workerData: i});    }    setInterval((a) => currentVal = counter(a,currentVal + 1), intervals[2], "MainThread");} else {    console.log("this isn't")    setInterval((a) => currentVal = counter(a,currentVal + 1), intervals[workerData], workerData);}

转载地址:https://blog.csdn.net/weixin_34248258/article/details/88802538 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:习惯不同语言以太坊开发者可选择客户端
下一篇:七种功能强大的聊天机器人平台

发表评论

最新留言

不错!
[***.144.177.141]2024年04月16日 03时51分42秒