Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Avoid double locking when sharing `Stdout` across threads
I 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:
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
.W: Write + Send + Clone
, then clone the W
and send a copy to each thread. However, Stdout
does not implement Clone
.Is there a way to handle this?
2 posts - 2 participants
🏷️ Rust_feed