-
Hi, I want to read/write to a TcpStream with a shared reference, but got stuck because TcpStream I want to use To construct a Two questions I'd like to ask:
pub fn split<'a>(&'a mut self) -> (ReadHalf<'a>, WriteHalf<'a>) {
split(self)
}
///
pub(crate) fn split(stream: &mut TcpStream) -> (ReadHalf<'_>, WriteHalf<'_>) {
(ReadHalf(&*stream), WriteHalf(&*stream))
} The definitions of both halves: #[derive(Debug)]
pub struct WriteHalf<'a>(&'a TcpStream);
#[derive(Debug)]
pub struct ReadHalf<'a>(&'a TcpStream); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
There is a reason behind it taking a mutable reference. Consider what happens if you try to read simultaneously from two references to the same
This poses a problem. It is not possible for both calls to All that said, since introducing the To answer your first question as well, it would be possible to construct a wrapper around |
Beta Was this translation helpful? Give feedback.
There is a reason behind it taking a mutable reference. Consider what happens if you try to read simultaneously from two references to the same
TcpStream
. Ultimately these two reads will result in both tasks callingpoll_read
on the sameTcpStream
, but all poll methods behave like the following (taken fromFuture::poll
):This poses a problem. It is not possible for both calls to
poll_read
to be the most recent caller simultaneously, and this means that one of them wont be woken up, which essentially means that its call to read will hang forever. Mu…