问题
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