Reentrancy in JavaScript

女生的网名这么多〃 提交于 2019-12-22 03:47:14

问题


I would like to improve my understanding of the word reentrant.

Is this function reentrant?

function* foo() {
  yield 1;
  yield 2;
}

And this one?

function foo() {
  return 1;
}

And this one?

var x = 0;
function foo() {
  return x++;
}

And this one?

function foo() {
  setTimeout(foo, 1000);
}

回答1:


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.



来源:https://stackoverflow.com/questions/34129978/reentrancy-in-javascript

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