使时间密集型功能异步 [英] Make time intensive function asynchronous

查看:112
本文介绍了使时间密集型功能异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使时间密集型功能(例如图像处理)异步运行以允许其他代码运行或允许该功能的多个实例并行运行的最佳方法是什么?(可能是特定于节点的),例如fs.readFile()或fetch()(XHR).

What's the best way to make a time intensive function, such as image manipulation, run asynchronously to allow other code to run or to allow multiple instances of said function run in parallel? (can be Node specific) For example like fs.readFile() or fetch() (XHR).

推荐答案

如果当前您的计算密集型图像处理全部是Javascript,那么node.js将Javascript作为单线程运行(一次只能执行一个Javascript).代码,然后与其他Javascript并行运行图像处理的选项如下:

Because node.js runs your Javascript as single threaded (only one piece of Javascript ever executing at a time), if your compute intensive image manipulation is currently all Javascript code, then your options for running your image manipulation in parallel with other Javascript are as follows:

  1. 启动一个或多个工作进程(可以运行node.js代码或您想要的任何其他程序),并在一个单独的进程中进行图像处理.然后,他们可以使用任何形式的进程间通信来回传结果.这可能是解决node.js中CPU密集型问题的最常用方法(将CPU密集型内容卸载到其他进程).您可以使用child_process模块​​来启动其他进程并与之通信.

  1. Fire up one or more worker processes (which can run node.js code or any other program you want) and do the image manipulation there in a separate process. They can then communicate back the result with any form of interprocess communication. This is probably the most common way to solve CPU intensive issues in node.js (offloading the CPU intensive stuff to other processes). You can use the child_process module to start these other processes and to communicate with them.

为node.js编写本机代码插件,该插件使用本机线程和本机代码进行图像处理,并提供与node.js代码的异步接口.然后,您可以从node.js异步调用该接口,并在完成时收到通知,但是node.js在工作时可以自由进行其他工作.

Write a native code add-on for node.js that uses native threads and native code to do the image manipulation and that offers an asynchronous interface to node.js code. You can then call that interface asynchronously from node.js and be notified when it is complete, but node.js will be free to work on other things while it is working.

将图像处理分成非常小的工作块,这样您就可以执行一小部分工作(例如几毫秒的工作),安排下一个工作块在其中运行几毫秒,并将控制权返回给事件子系统,以便它可以处理与您的小块工作交织在一起的其他事件.仅供参考,设计复杂的代码以小块运行很难.您最终必须构建一个状态机,该状态机可以执行少量工作并返回,然后稍后再调用它来执行更多工作.

Break the image manipulation into very small work chunks such that you can execute a small chunk of work (like a few ms of work), schedule the next chunk of work to run in a few ms and return control back to the event sub-system so it can process other events interleaved with your small chunks of work. FYI, design complicated code to run in small chunks is hard. You end up having to essentially build a state machine that can do a small amount of work and return, only to be called later to do some more work.

这篇关于使时间密集型功能异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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