Skip to content

Commit

Permalink
Auto merge of #54806 - parched:park, r=RalfJung
Browse files Browse the repository at this point in the history
thread::unpark: Avoid notifying with mutex locked.

This means when the other thread wakes it can continue right away
instead of having to wait for the mutex.

Also add some comments explaining why the mutex needs to be locked in
the first place.

This is a follow up to #54174
I did some tests with relacy [here](https://gist.github.com/parched/b7fb88c97755a81e5cb9f9048a15f7fb) (This PR is InnerV2). If anyone can think of some other test case worth adding let me know.

r? @RalfJung
  • Loading branch information
bors committed Oct 31, 2018
2 parents 05812fa + d3e71e4 commit de9666f
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/libstd/thread/mod.rs
Expand Up @@ -1149,8 +1149,18 @@ impl Thread {
_ => panic!("inconsistent state in unpark"),
}

// Coordinate wakeup through the mutex and a condvar notification
let _lock = self.inner.lock.lock().unwrap();
// There is a period between when the parked thread sets `state` to
// `PARKED` (or last checked `state` in the case of a spurious wake
// up) and when it actually waits on `cvar`. If we were to notify
// during this period it would be ignored and then when the parked
// thread went to sleep it would never wake up. Fortunately, it has
// `lock` locked at this stage so we can acquire `lock` to wait until
// it is ready to receive the notification.
//
// Releasing `lock` before the call to `notify_one` means that when the
// parked thread wakes it doesn't get woken only to have to wait for us
// to release `lock`.
drop(self.inner.lock.lock().unwrap());
self.inner.cvar.notify_one()
}

Expand Down

0 comments on commit de9666f

Please sign in to comment.