本文介绍了关于异步方法和线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
异步函数的幕后究竟发生了什么?
它是否打开一个新线程并让操作系统启动并运行它?
如果是这样,是否会导致死锁或其他线程问题?
以下是异步方法的示例:
var fs = require('fs')var 文件 = process.argv[2]fs.readFile(文件,函数(错误,内容){var lines = contents.toString().split('\n').length - 1控制台日志(行)})
解决方案
在 fs.readFile(file,callback)
中.这是一个非阻塞调用,这意味着.
- node 的主线程将
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.
- node's main thread stores the
callback
in event-table andassociate it with an event which will be emitted whenever filereading process is done. - By the same time node has several internal threads(thread pool) fromwhich node's main thread assign file reading task to one of thethread.
- After this assignment the command is returned to main thread andmain thread continues with the other tasks and file reading processis being done in background by other thread(not main thread).
- Whenever file reading process is completed the event associated withthe
callback
is emitted along with the data from file and thatcallback is pushed intotask-queue
where event loop tries to pusheach task to the main thread(stack). - And when main thread(stack) becomes available and and there is notask present before the
callback
's task this callback is pushed tomain 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
这篇关于关于异步方法和线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!