Reentrancy in JavaScript

不想你离开。 提交于 2019-12-05 03:02:07

A reentrent function is a function whose execution can be resumed:

In computing, a computer program or subroutine is called reentrant if it can be interrupted in the middle of its execution and then safely called again ("re-entered") before its previous invocations complete execution.

In browser/node JavaScript, all multiprocessing is cooperative (no interrupts or context switches). A regular function always runs to completion in JavaScript. (1)

So in your case - the only reentrent function is the first one since it doesn't run its code to completion and can be resumed at a later point.

  • The second function is just a regular function.
  • The third one uses an outer scope, which is kind of similar because it lets a function hold some state. It's not the same thing though since the function can't be resumed.
  • The fourth one just runs to completion immediately (it schedules another invokation of it - but that's up to the platform and not JavaScript).

Indeed - one can say that generators enable cooperative multitasking in JavaScript with a reentrent syntax. Before generators all code ran to completion.

(1) Or it never halts, but it is never interrupted. Also - in common platforms. There are platforms (like Rhino) that break the rule. They're very rare and don't use the same concurrency execution model as browser/node JS.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!