Busy Waiting In Nodejs
Solution 1:
Javascript is single threaded‡. Therefore any form of busy waiting will cause the thread to completely block preventing it from entering the event loop which means no event gets processed.
At the C level, the interpreter is very simple. Since it is single threaded it does not need any complicated logic, just a single infinite while loop. In pseudocode it goes something like this:
do {
event_queue = execute_javascript()
completed_events = wait_for_events()
for_each (eventfrom completed_events) {
this_event = event_queue.find_one_matching(event)
execute_javascript(this_event.callback)
}
} while (there_is_pending_events)
As you can see, nothing in the interpreter runs in parallel. They all run sequentially. Asynchronous code waits in parallel but does not execute in parallel.
In your code, the while(){}
loop gets stuck in execute_javascript()
which will not return until your while loop completes. This means the interpreter is stuck.
Adding an await
inside the while(){}
loop causes execute_javascript()
to return at the await (and will continue again at the line after await
) allowing the interpreter to continue waiting for events at wait_for_events()
.
‡ Note: There are people who will tell you that javascript uses background threads to process asynchronous code. They are wrong. Node.js (not browsers) does use one, single, additional thread to process disk I/O but only disk I/O. Network I/O is done in the main thread like I describe above. The disk I/O is done that way because there is very little compatibility for asynchronous disk I/O API between Windows, Linux and BSD (BSD includes Mac OSX)
If you are interested in much lower level explanation for how the event loop and asynchronous code execution works in javascript you may be interested in my answers to these other related questions. In some I explain down to the level of how the hardware handles it. In some I explore how it's done in C/C++:
Is my understanding of asynchronous operations correct?
Is there any other way to implement a "listening" function without an infinite while loop?
node js - what happens to incoming events during callback excution
Solution 2:
For the first function fn1
, you put async
before the function, but with fn2
you did not. Try removing that from the first function and see if it still remains stuck.
Post a Comment for "Busy Waiting In Nodejs"