Skip to content

Commit de9666f

Browse files
committed
Auto merge of #54806 - parched:park, r=RalfJung
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
2 parents 05812fa + d3e71e4 commit de9666f

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)