问题描述
我决定使自己熟悉node.js,并阅读了有关该主题的几篇文章.我仍然不清楚的是,当您调用node.js函数时,node.js是否在线程池中创建新线程和/或在线程上调度任务.
I've decided to familiarize myself with node.js and have read a several articles on the subject. What remained unclear to me is if node.js creates new threads and/or schedules tasks on threads from a thread pool when you call node.js functions.
例如,如果我调用fs.readFile
,它是否在其他线程上执行?
For example if I call fs.readFile
is it executed on a different thread?
如果是,[如何]我可以编写自己的函数readFileCustomized
或doLongOperation
在不同的线程上运行?
If yes, [how] can I write my own function readFileCustomized
or doLongOperation
to run on a different thread?
推荐答案
没有用于文件操作的异步API,因此node.js为此使用了线程池.您可以在 libuv 的代码中看到它.
There is no async API for file operations so node.js uses a thread pool for that. You can see it in the code of libuv.
static uv_thread_t default_threads[4];
阻塞FS任务发布到 uv__work_submit .例如,这是实现 read的方式:
Blocking FS tasks are posted with uv__work_submit. For example, here's how read is implemented:
int uv_fs_read(uv_loop_t* loop, uv_fs_t* req,
uv_file file,
void* buf,
size_t len,
int64_t off,
uv_fs_cb cb) {
INIT(READ);
req->file = file;
req->buf = buf;
req->len = len;
req->off = off;
POST;
}
...
#define POST \
do { \
if ((cb) != NULL) { \
uv__work_submit((loop), &(req)->work_req, uv__fs_work, uv__fs_done); \
return 0; \
} \
else { \
uv__fs_work(&(req)->work_req); \
uv__fs_done(&(req)->work_req, 0); \
return (req)->result; \
} \
} \
while (0)
如果要实现自己的线程,可以查看详细介绍.
If you want to implement your own threads, you can check this great introduction.
这篇关于node.js是否在内部使用线程/线程池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!