简体   繁体   English

console.log 是原子的吗?

[英]Is console.log atomic?

The print statement in Python is not thread-safe. Python 中的print语句不是线程安全的。 Is it safe to use console.log in Node.js concurrently?在 Node.js 中同时使用console.log是否安全?

If so, then is it also interleave-safe?如果是这样,那么它也是交错安全的吗? That is, if multiple (even hundreds) of callbacks write to the console, can I be sure that the output won't be clobbered or interleaved?也就是说,如果多个(甚至数百个)回调写入控制台,我能确定输出不会被破坏或交错吗?

Looking at the source code, it seems that Node.js queues concurrent attempts to write to a stream ( here ).查看源代码,Node.js 似乎将写入流的并发尝试排队( 此处)。 On the other hand, console.log 's substitution flags come from printf(3) .另一方面, console.log替换标志来自printf(3) If console.log wraps around printf , then that can interleave output on POSIX machines ( as shown here ).如果console.log环绕printf ,那么它可以在 POSIX 机器上交错输出(如此处所示)。

Please show me where the async ._write(chunk, encoding, cb) is implemented inside Node.js in your response to this question.请告诉我async ._write(chunk, encoding, cb)在 Node.js 中在您对此问题的回答中实现的位置。

EDIT: If it is fine to write to a stream concurrently, then why does this npm package exist?编辑:如果可以同时写入流,那么为什么这个 npm 包存在?

Everything in node.js is basically "atomic". node.js 中的一切基本上都是“原子的”。 That's because node.js is single threaded - no code can ever be interrupted.那是因为 node.js 是单线程的——任何代码都不能被中断。

The events loop of nodejs is single thread, but all the async calls of nodejs are multi-threaded, it use libuv under the hood, libuv is library that use multi threads. nodejs 的事件循环是单线程的,但是 nodejs 的所有异步调用都是多线程的,它底层使用 libuv,libuv 是使用多线程的库。

link: https://medium.com/the-node-js-collection/what-you-should-know-to-really-understand-the-node-js-event-loop-and-its-metrics-c4907b19da4c链接: https : //medium.com/the-node-js-collection/what-you-should-know-to-really-understand-the-node-js-event-loop-and-its-metrics-c4907b19da4c

Based on what I see on my Node.js console it is NOT "interleave-safe".根据我在 Node.js 控制台上看到的内容,它不是“交错安全”。

I can see my console-output is sometimes "clobbered or interleaved".我可以看到我的控制台输出有时被“破坏或交错”。 Not always.并非总是如此。 When I run my program it is maybe every 5th time that I see interleaved output from multiple log-statements.当我运行我的程序时,我可能每 5 次看到多个日志语句的交错输出。

This may of course depend on your Node.js version and the OS you are running it on.这当然可能取决于您的 Node.js 版本和运行它的操作系统。 For the record my Node.js version is v12.13.0 and OS is Windows 10.0.19042.作为记录,我的 Node.js 版本是 v12.13.0,操作系统是 Windows 10.0.19042。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM