Replies: 1 comment
-
|
Your intuition about But unsafe impl<T: Send> Send for ReadHalf<T> {}
unsafe impl<T: Send> Send for WriteHalf<T> {}
unsafe impl<T: Sync> Sync for ReadHalf<T> {}
unsafe impl<T: Sync> Sync for WriteHalf<T> {}So the compiler is not “figuring it out” from the internal In practice, for the common use case you usually don’t need let (read_half, write_half) = tokio::io::split(stream);
tokio::spawn(async move {
// use read_half here
});
tokio::spawn(async move {
// use write_half here
});
If your own code requires If you really need shared access, wrap the half outside: use std::sync::{Arc, Mutex};
let read_half = Arc::new(Mutex::new(read_half));Then the wrapper can be So tl;dr: the internal mutex could allow a looser bound, but Tokio’s public impl is intentionally/conservatively |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello everyone,
I’m currently learning Rust and working on some I/O-related demos using Tokio. While exploring the split functionality provided by tokio-util, I encountered an issue: when I try to split a type T that implements Send but not Sync, I get a compilation error saying that ReadHalf or WriteHalf does not implement Sync.
This surprised me, because when I checked the source code, I noticed that these types internally use std::sync::Mutex, which I assumed would make them thread-safe. However, I later discovered that both ReadHalf and WriteHalf use an unsafe block to implement Sync, but only if T: Sync.
Here are my questions:
1.Why do ReadHalf and WriteHalf require T: Sync to implement Sync, even though they wrap T inside a Mutex? My type is Send, and I’m not accessing T concurrently outside of the Mutex. Is there a specific safety or design reason for this restriction?
2.Why doesn’t the compiler automatically derive Sync for ReadHalf / WriteHalf, relying on the safety of the Mutex? Why does Tokio use a manual unsafe impl Sync for ReadHalf and explicitly require T: Sync? Isn’t the Mutex supposed to guarantee thread-safety regardless of whether T is Sync?
Beta Was this translation helpful? Give feedback.
All reactions