About asynchronous methods and threads

橙三吉。 提交于 2019-12-25 07:50:02

问题


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.

  1. 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.
  2. 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.
  3. 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).
  4. 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 into task-queue where event loop tries to push each task to the main thread(stack).
  5. 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

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