You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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?
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
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