gpt4 book ai didi

multithreading - node.js 是否在内部使用线程/线程池?

转载 作者:搜寻专家 更新时间:2023-10-31 22:39:21 25 4
gpt4 key购买 nike

我决定熟悉 node.js 并阅读了多篇有关该主题的文章。我仍然不清楚的是,当您调用 node.js 函数时,node.js 是否会创建新线程和/或在线程池中的线程上安排任务。

例如,如果我调用 fs.readFile,它是否在不同的线程上执行?

如果是,[如何]编写自己的函数 readFileCustomizeddoLongOperation 以在不同的线程上运行?

最佳答案

没有用于文件操作的异步 API,因此 node.js 为此使用线程池。在libuv的代码中可以看到.

The pool can run 4 threads :

static uv_thread_t default_threads[4];

阻塞 FS 任务发布为 uv__work_submit .例如,这里是 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)

如果你想实现你自己的线程,你可以查看这个great introduction .

关于multithreading - node.js 是否在内部使用线程/线程池?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20346097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com