@@ -206,6 +206,31 @@ 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,ignore
216+ impl<T> Drop for Carton<T> {
217+ fn drop(&mut self) {
218+ unsafe {
219+ libc::free(self.0.as_ptr().cast());
220+ }
221+ }
222+ }
223+ ```
224+
225+ A nice example where this does not happen is with a MutexGuard: notice how
226+ [ it is not Send] [ mutex-guard-not-send-docs-rs ] . The implementation of MutexGuard
227+ [ uses libraries] [ mutex-guard-not-send-comment ] that require you to ensure you
228+ don't try to free a lock that you acquired in a different thread. If you were
229+ able to Send a MutexGuard to another thread the destructor would run in the
230+ thread you sent it to, violating the requirement. MutexGuard can still be sync
231+ because all you can send to another thread is an ` &MutexGuard ` and dropping a
232+ reference does nothing.
233+
209234TODO: better explain what can or can't be Send or Sync. Sufficient to appeal
210235only to data races?
211236
@@ -214,3 +239,5 @@ only to data races?
214239[ box-is-special ] : https://manishearth.github.io/blog/2017/01/10/rust-tidbits-box-is-special/
215240[ deref-doc ] : https://doc.rust-lang.org/core/ops/trait.Deref.html
216241[ deref-mut-doc ] : https://doc.rust-lang.org/core/ops/trait.DerefMut.html
242+ [ mutex-guard-not-send-docs-rs ] : https://doc.rust-lang.org/std/sync/struct.MutexGuard.html#impl-Send
243+ [ mutex-guard-not-send-comment ] : https://github.com/rust-lang/rust/issues/23465#issuecomment-82730326
0 commit comments