Skip to content

Commit

Permalink
!Send + Sync without unsafe!
Browse files Browse the repository at this point in the history
thanks @MikailBag for the suggestion!

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
  • Loading branch information
hawkw committed Sep 29, 2020
1 parent 7eef5d3 commit 81e9e5b
Showing 1 changed file with 2 additions and 19 deletions.
21 changes: 2 additions & 19 deletions tracing/src/span.rs
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@ pub(crate) struct Inner {
#[must_use = "once a span has been entered, it should be exited"]
pub struct Entered<'a> {
span: &'a Span,
_not_send: PhantomData<*mut ()>,
_not_send: PhantomData<crate::stdlib::sync::MutexGuard<'static, ()>>,
}

/// `log` target for all span lifecycle (creation/enter/exit/close) records.
Expand Down Expand Up @@ -1235,24 +1235,6 @@ impl Clone for Inner {

// ===== impl Entered =====

/// # Safety
///
/// Technically, `Entered` _can_ implement both `Send` *and* `Sync` safely. It
/// doesn't, because it has a `PhantomData<*mut ()>` field, specifically added
/// in order to make it `!Send`.
///
/// Sending an `Entered` guard between threads cannot cause memory unsafety.
/// However, it *would* result in incorrect behavior, so we add a
/// `PhantomData<*mut ()>` to prevent it from being sent between threads. This
/// is because it must be *dropped* on the same thread that it was created;
/// otherwise, the span will never be exited on the thread where it was entered,
/// and it will attempt to exit the span on a thread that may never have entered
/// it. However, we still want them to be `Sync` so that a struct holding an
/// `Entered` guard can be `Sync`.
///
/// Thus, this is totally safe.
unsafe impl<'a> Sync for Entered<'a> {}

impl<'a> Drop for Entered<'a> {
#[inline]
fn drop(&mut self) {
Expand Down Expand Up @@ -1313,4 +1295,5 @@ mod test {

trait AssertSync: Sync {}
impl AssertSync for Span {}
impl<'a> AssertSync for Entered<'a> {}
}

0 comments on commit 81e9e5b

Please sign in to comment.