Skip to content

Commit d3e71e4

Browse files
author
James Duley
committed
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.
1 parent e8aef7c commit d3e71e4

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

src/libstd/thread/mod.rs

+12-2
Original file line numberDiff line numberDiff line change
@@ -1149,8 +1149,18 @@ impl Thread {
11491149
_ => panic!("inconsistent state in unpark"),
11501150
}
11511151

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

0 commit comments

Comments
 (0)