问题
What actually happens behind the scenes with asynchronous functions?
Does it open a new thread and let the OS start and run it?
If so, can it cause deadlocks or other thread problems?
Here's an example of a async method:
var fs = require('fs')
var file = process.argv[2]
fs.readFile(file, function (err, contents) {
var lines = contents.toString().split('\n').length - 1
console.log(lines)
})
回答1:
In fs.readFile(file,callback)
.This is a non-blocking call which means.
- node's main thread stores the
callback
in event-table and associate it with an event which will be emitted whenever file reading process is done. - By the same time node has several internal threads(thread pool) from which node's main thread assign file reading task to one of the thread.
- After this assignment the command is returned to main thread and main thread continues with the other tasks and file reading process is being done in background by other thread(not main thread).
- Whenever file reading process is completed the event associated with
the
callback
is emitted along with the data from file and that callback is pushed intotask-queue
where event loop tries to push each task to the main thread(stack). - And when main thread(stack) becomes available and and there is no
task present before the
callback
's task this callback is pushed to main thread's stack by the event-loop.
Please read event-loop for more info.
So the thread which is responsible for file reading doesnt cause Deadlock to othere threads.
It simply emit exception or success which is later handled by the callback
来源:https://stackoverflow.com/questions/38971952/about-asynchronous-methods-and-threads