关于异步方法和线程 [英] About asynchronous methods and threads

查看:48
本文介绍了关于异步方法和线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

异步函数的幕后究竟发生了什么?

它是否打开一个新线程并让操作系统启动并运行它?

如果是这样,是否会导致死锁或其他线程问题?

以下是异步方法的示例:

var fs = require('fs')var 文件 = process.argv[2]fs.readFile(文件,函数(错误,内容){var lines = contents.toString().split('\n').length - 1控制台日志(行)})

解决方案

fs.readFile(file,callback) 中.这是一个非阻塞调用,这意味着.

  1. node 的主线程将 callback 存储在 event-table 和将它与一个事件相关联,该事件将在文件读取过程完成.
  2. 同时节点有几个内部线程(线程池)来自哪个节点的主线程将文件读取任务分配给其中之一线程.
  3. 在此分配后,命令返回到主线程并主线程继续执行其他任务和文件读取过程正在由其他线程(不是主线程)在后台完成.
  4. 每当文件读取过程完成时,与callback 与文件中的数据一起发出,并且回调被推送到 task-queue 中,事件循环试图推送每个任务到主线程(堆栈).
  5. 当主线程(堆栈)可用并且没有任务出现在 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.

  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

这篇关于关于异步方法和线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆