@@ -206,6 +206,32 @@ sort of Box would be Send, which in this case is the same as saying T is Send.
206206unsafe impl <T > Send for Carton <T > where Box <T >: Send {}
207207```
208208
209+ Right now Carton<T > has a memory leak, as it never frees the memory it allocates.
210+ Once we fix that we have a new requirement we have to ensure we meet to be Send:
211+ we need to know ` free ` can be called on a pointer that was yielded by an
212+ allocation done on another thread. This is the case for ` libc::free ` , so we can
213+ still be Send.
214+
215+ ``` rust
216+ # struct Carton <T >(std :: ptr :: NonNull <T >);
217+ impl <T > Drop for Carton <T > {
218+ fn drop (& mut self ) {
219+ unsafe {
220+ libc :: free (self . 0. as_ptr (). cast ());
221+ }
222+ }
223+ }
224+ ```
225+
226+ A nice example where this does not happen is with a MutexGuard: notice how
227+ [ it is not Send] [ mutex-guard-not-send-docs-rs ] . The implementation of MutexGuard
228+ [ uses libraries] [ mutex-guard-not-send-comment ] that require you to ensure you
229+ don't try to free a lock that you acquired in a different thread. If you were
230+ able to Send a MutexGuard to another thread the destructor would run in the
231+ thread you sent it to, violating the requirement. MutexGuard can still be sync
232+ because all you can send to another thread is an ` &MutexGuard ` and dropping a
233+ reference does nothing.
234+
209235TODO: better explain what can or can't be Send or Sync. Sufficient to appeal
210236only to data races?
211237
@@ -214,3 +240,5 @@ only to data races?
214240[ box-is-special ] : https://manishearth.github.io/blog/2017/01/10/rust-tidbits-box-is-special/
215241[ deref-doc ] : https://doc.rust-lang.org/core/ops/trait.Deref.html
216242[ deref-mut-doc ] : https://doc.rust-lang.org/core/ops/trait.DerefMut.html
243+ [ mutex-guard-not-send-docs-rs ] : https://doc.rust-lang.org/std/sync/struct.MutexGuard.html#impl-Send
244+ [ mutex-guard-not-send-comment ] : https://github.com/rust-lang/rust/issues/23465#issuecomment-82730326
0 commit comments