问题描述
限时送ChatGPT账号..异步函数的幕后究竟发生了什么?
它是否打开一个新线程并让操作系统启动并运行它?
如果是这样,是否会导致死锁或其他线程问题?
以下是异步方法的示例:
var fs = require('fs')var 文件 = process.argv[2]fs.readFile(文件,函数(错误,内容){var lines = contents.toString().split('\n').length - 1控制台日志(行)})
解决方案 在 fs.readFile(file,callback)
中.这是一个非阻塞调用,这意味着.
callback
存储在 event-table 和将它与一个事件相关联,该事件将在文件读取过程完成.同时节点有几个内部线程(线程池)来自哪个节点的主线程将文件读取任务分配给其中之一线程.在此分配后,命令返回到主线程并主线程继续执行其他任务和文件读取过程正在由其他线程(不是主线程)在后台完成.每当文件读取过程完成时,与callback
与文件中的数据一起发出,并且回调被推送到 task-queue
中,事件循环试图推送每个任务到主线程(堆栈).当主线程(堆栈)可用并且没有任务出现在 callback
的任务之前,这个回调被推送到事件循环的主线程堆栈.请阅读事件循环了解更多信息.>
因此负责文件读取的线程不会导致其他线程死锁.它只是发出异常或成功,稍后由 callback
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)
})
解决方案
In fs.readFile(file,callback)
.This is a non-blocking call which means.
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 into task-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
这篇关于关于异步方法和线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论