简体   繁体   中英

Is console.log atomic?

The print statement in Python is not thread-safe. Is it safe to use console.log in Node.js concurrently?

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 ). On the other hand, console.log 's substitution flags come from printf(3) . If console.log wraps around printf , then that can interleave output on POSIX machines ( as shown here ).

Please show me where the async ._write(chunk, encoding, cb) is implemented inside Node.js in your response to this question.

EDIT: If it is fine to write to a stream concurrently, then why does this npm package exist?

Everything in node.js is basically "atomic". That's because node.js is single threaded - no code can ever be interrupted.

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.

link: 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".

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.

This may of course depend on your Node.js version and the OS you are running it on. For the record my Node.js version is v12.13.0 and OS is Windows 10.0.19042.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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