Commit 476798d
authored
Rollup merge of rust-lang#99587 - ibraheemdev:park-orderings, r=m-ou-se
Document memory orderings of `thread::{park, unpark}`
Document `thread::park/unpark` as having acquire/release synchronization. Without that guarantee, even the example in the documentation can deadlock:
```rust
let flag = Arc::new(AtomicBool::new(false));
let t2 = thread::spawn(move || {
while !flag.load(Ordering::Acquire) {
thread::park();
}
});
flag.store(true, Ordering::Release);
t2.thread().unpark();
// t1: flag.store(true)
// t1: thread.unpark()
// t2: flag.load() == false
// t2 now parks, is immediately unblocked but never
// acquires the flag, and thus spins forever
```
Multiple calls to `unpark` should also maintain a release sequence to make sure operations released by previous `unpark`s are not lost:
```rust
let a = Arc::new(AtomicBool::new(false));
let b = Arc::new(AtomicBool::new(false));
let t2 = thread::spawn(move || {
while !a.load(Ordering::Acquire) || !b.load(Ordering::Acquire) {
thread::park();
}
});
thread::spawn(move || {
a.store(true, Ordering::Release);
t2.thread().unpark();
});
b.store(true, Ordering::Release);
t2.thread().unpark();
// t1: a.store(true)
// t1: t2.unpark()
// t3: b.store(true)
// t3: t2.unpark()
// t2 now parks, is immediately unblocked but never
// acquires the store of `a`, only the store of `b` which
// was released by the most recent unpark, and thus spins forever
```
This is of course a contrived example, but is reasonable to rely upon in real code.
Note that all implementations of park/unpark already comply with the rules, it's just undocumented.1 file changed
+21
-11
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
889 | 889 | | |
890 | 890 | | |
891 | 891 | | |
892 | | - | |
| 892 | + | |
893 | 893 | | |
894 | 894 | | |
895 | 895 | | |
| |||
910 | 910 | | |
911 | 911 | | |
912 | 912 | | |
913 | | - | |
914 | | - | |
915 | | - | |
916 | | - | |
917 | | - | |
918 | | - | |
919 | | - | |
920 | | - | |
921 | 913 | | |
922 | 914 | | |
923 | 915 | | |
| |||
931 | 923 | | |
932 | 924 | | |
933 | 925 | | |
| 926 | + | |
| 927 | + | |
| 928 | + | |
| 929 | + | |
| 930 | + | |
| 931 | + | |
| 932 | + | |
| 933 | + | |
| 934 | + | |
| 935 | + | |
| 936 | + | |
| 937 | + | |
| 938 | + | |
| 939 | + | |
| 940 | + | |
| 941 | + | |
| 942 | + | |
934 | 943 | | |
935 | 944 | | |
936 | 945 | | |
| |||
944 | 953 | | |
945 | 954 | | |
946 | 955 | | |
947 | | - | |
| 956 | + | |
948 | 957 | | |
949 | 958 | | |
950 | 959 | | |
| |||
961 | 970 | | |
962 | 971 | | |
963 | 972 | | |
964 | | - | |
| 973 | + | |
965 | 974 | | |
966 | 975 | | |
967 | 976 | | |
| |||
970 | 979 | | |
971 | 980 | | |
972 | 981 | | |
| 982 | + | |
973 | 983 | | |
974 | 984 | | |
975 | 985 | | |
| |||
0 commit comments