'Concurrent read/write on tokio TcpStream
I have a scenario where thread 1 writes to the socket, thread 2 reads from the socket. I have done this in the past via split() which would consume the TcpStream and return the ReadHalf/WriteHalf, which then could be neatly passed to the threads. I am running into issues on 1.39.0(tokio - 0.2.0-alpha.6).
Now it has changed to
pub fn split(&mut self) -> (ReadHalf, WriteHalf). This doesn't allow passing the ReadHalf/WriteHalf(whose lifetime is tied to the stream) to separate threads, without running into messy lifetime issuesThe plain
read()/write()variants take&mut self, which makes it impossible to do concurrent reads/writes.
Interestingly, UdpSocket still has the old way(pub fn split(self) -> (UdpSocketRecvHalf, UdpSocketSendHalf))
Also found this related(unresolved) thread: https://github.com/tokio-rs/tokio/issues/1108. Not sure it is even possible anymore with TcpStream.
Appreciate any suggestions here.
Thanks.
Solution 1:[1]
You can use tokio::io::split
let (read, write) = tokio::io::split(socket);
This ends into ReadHalf and WriteHalf, both of which implement Send and Sync.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mika Vatanen |
