Avoid double locking when sharing `Stdout` across threads
⚓ Rust 📅 2025-08-12 👤 surdeus 👁️ 10I have a program where I have multiple threads writing to the same io. The multithreaded writing function is generic over the writer type W: Write + Send, but the type defaults to stdout.
Currently, I handle this by sending an Arc<Mutex<W>> to each thread. That works fine, and I should probably just leave it at that.
However, I noticed that the Stdout type itself contains a Mutex. So, my current solution locks twice on each write: First it locks the mutex I created to access the Stdout, and then it locks the Stdout. I wonder if there is a way to only make it lock once for Stdout, while still having the function be generic over writer types.
I've tried the following things:
- Share an
Arc<W> where for<'a> &'a T: Write. This doesn't work, because even though&W: Write, I still need a mutable reference to actually call.write. - Require
W: Write + Send + Clone, then clone theWand send a copy to each thread. However,Stdoutdoes not implementClone.
Is there a way to handle this?
2 posts - 2 participants
🏷️ Rust_feed