Skip to content

Why does writing to stdout/stderr from multiple threads results in interleaved output? #321

Answered by BurntSushi
jpmckinney asked this question in Q&A
Discussion options

You must be logged in to vote

This is absolutely expected behavior. Your println! code is not equivalent. When you call println!, it's internally calling std::io::stdout().lock(). The csv::Writer does no such thing. All it takes is something that implements std::io::Write. There's no lock() method to call in that context. Instead, it's up to you, the caller, to either pass a locked writer or manage the synchronization yourself.

Basically, you're creating a bunch of threads, each with their own CSV writer, but on top of the same underlying std::io::Write implementation. The CSV writer might call write multiple times on the given writer for each serialize call, and thus the output is interleaved. And it is expected and …

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@jpmckinney
Comment options

Answer selected by jpmckinney
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #320 on May 18, 2023 17:27.