flynnel 0.6.0

K-aware NUMA-aware work-stealing scheduler with extended-Flynn-taxonomy dispatch (MIMD / SIMC / MIMC / MISD / SIMT / MIMT): a rayon-shaped pool reshaped around per-call execution-class plans with first-class CPU+GPU hybrid (join_hybrid, hybrid_pipeline) and per-call dispatch profiles.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
//! 4-state core latch + `Latch` trait with self-invalidation discipline.
//!
//! Direct adaptation of rayon-core 1.13's `latch.rs` shape, reshaped
//! for Flynnel. The state machine and the `Latch::set(*const Self)`
//! contract are borrowed verbatim because the design has been
//! battle-hardened in rayon across a decade of edge cases.
//!
//! ## State machine
//!
//! ```text
//!   UNSET ----get_sleepy()---> SLEEPY ----fall_asleep()---> SLEEPING
//!     |                          |                              |
//!     |                          |                              |
//!     v                          v                              v
//!    SET (Latch::set called; publisher observed prior state)
//! ```
//!
//! Transitions are all CAS with SeqCst on success, Relaxed on failure.
//! `Latch::set` is a `swap(SET, AcqRel)` that returns the prior state;
//! the publisher uses the return value to decide whether to wake a
//! parked worker (only needed when prior was `SLEEPING`).
//!
//! ## The self-invalidation contract
//!
//! `Latch::set` takes `*const Self` rather than `&self` because the
//! publishing CAS may wake a thread that immediately deallocates the
//! latch (e.g., when a `StackJob` finishes and its parent frame
//! returns). Implementations must read every field they need before
//! the publishing store; `SpinLatch::set` does this by copying
//! `target_worker_index` to a local first, and `CountLatch` /
//! `LockLatch` follow the same discipline.
//!

use core::sync::atomic::{AtomicU8, AtomicUsize, Ordering};

/// Latch not set; owning thread is awake.
const UNSET: u8 = 0;
/// Latch not set; owning thread is preparing to sleep but has not
/// committed yet. The publisher can still observe this state and
/// abort the park.
const SLEEPY: u8 = 1;
/// Latch not set; owning thread is parked on a condvar elsewhere
/// (the latch only owns the lifecycle marker). The publisher must
/// wake the parked thread after setting.
const SLEEPING: u8 = 2;
/// Latch is set. Terminal state.
const SET: u8 = 3;

/// One-time signaling primitive. Starts at [`UNSET`]; transitions
/// monotonically to [`SET`].
///
/// See module-level docs for the state machine and the
/// `set(*const Self)` self-invalidation contract.
#[derive(Debug)]
pub struct CoreLatch {
    state: AtomicU8,
}

impl Default for CoreLatch {
    fn default() -> Self {
        Self::new()
    }
}

impl CoreLatch {
    /// Construct a fresh latch in the `UNSET` state.
    #[inline]
    pub const fn new() -> Self {
        Self {
            state: AtomicU8::new(UNSET),
        }
    }

    /// The address of the state byte, for a monitor wait to watch the
    /// cache line it sits in. Every store that sets this latch, or
    /// moves it through the sleepy handshake, lands on that line.
    #[inline]
    pub(crate) fn line(&self) -> *const u8 {
        (&raw const self.state).cast::<u8>()
    }

    /// First phase of the sleep handshake. The owning thread calls
    /// this to declare intent to park. Returns `true` if the
    /// transition `UNSET -> SLEEPY` succeeded and the caller may
    /// proceed to [`Self::fall_asleep`]; returns `false` if the latch
    /// was already set in the meantime (caller should not park).
    #[inline]
    pub fn get_sleepy(&self) -> bool {
        self.state
            .compare_exchange(UNSET, SLEEPY, Ordering::SeqCst, Ordering::Relaxed)
            .is_ok()
    }

    /// Second phase of the sleep handshake. The owning thread calls
    /// this immediately before parking on its condvar. Returns `true`
    /// if the transition `SLEEPY -> SLEEPING` succeeded (caller may
    /// park); returns `false` if the latch was set after
    /// `get_sleepy` (caller must not park).
    #[inline]
    pub fn fall_asleep(&self) -> bool {
        self.state
            .compare_exchange(SLEEPY, SLEEPING, Ordering::SeqCst, Ordering::Relaxed)
            .is_ok()
    }

    /// Called by the owning thread after a wakeup that did not
    /// observe `SET` (e.g., a spurious condvar wake or the JEC-
    /// observed-injected-job path). Reverts `SLEEPING -> UNSET` so
    /// the thread can re-enter the work-search loop. No-op if the
    /// latch is already `SET`.
    #[inline]
    pub fn wake_up(&self) {
        if !self.is_set() {
            let _ = self.state.compare_exchange(
                SLEEPING,
                UNSET,
                Ordering::SeqCst,
                Ordering::Relaxed,
            );
        }
    }

    /// Test whether the latch has been set. Acquire-ordered so any
    /// effects published before [`Latch::set`] are visible.
    #[inline]
    pub fn is_set(&self) -> bool {
        self.state.load(Ordering::Acquire) == SET
    }

    /// Direct setter used by [`Latch::set`] impls. Returns `true` if
    /// the previous state was `SLEEPING` (publisher must wake the
    /// parked thread); `false` otherwise.
    ///
    /// # Safety
    ///
    /// Caller must ensure `this` points to a valid `CoreLatch` for
    /// the duration of the swap. After the swap returns, callers
    /// must not touch any field of `*this` except those captured by
    /// value BEFORE this call: a parked thread may wake and
    /// deallocate the latch as soon as it observes `SET`.
    #[inline]
    pub(crate) unsafe fn set(this: *const Self) -> bool {
        // SAFETY: the `# Safety` clause on this function shifts
        // the validity-of-`this` precondition onto the caller;
        // here we may deref it once for the publishing atomic
        // swap. We must not touch `*this` after the swap because
        // a parked thread observing SLEEPING -> SET is free to
        // deallocate the latch.
        let old = unsafe { (*this).state.swap(SET, Ordering::AcqRel) };
        old == SLEEPING
    }
}

/// Latches share the contract that exactly one [`Latch::set`] call
/// transitions the latch from "not set" to "set", at which point
/// every [`CoreLatch::is_set`] returns `true` (with happens-before
/// ordering of all effects sequenced before the set).
///
/// `set` takes `*const Self` rather than `&self` to allow the
/// pointed-to memory to become invalidated DURING the call (a
/// parked thread may wake and free the latch). See the module
/// docs for the discipline this imposes on implementations.
pub trait Latch {
    /// Set the latch. Implementations must read every field of
    /// `*this` they need BEFORE the publishing store; after that
    /// store, `*this` may be invalidated.
    ///
    /// # Safety
    ///
    /// The caller asserts that `this` points to a valid `Self`
    /// upon entry and that no other code path will invalidate it
    /// during this call except for actions triggered by `set`
    /// itself (i.e., a parked thread waking and deallocating).
    unsafe fn set(this: *const Self);
}

impl Latch for CoreLatch {
    #[inline]
    unsafe fn set(this: *const Self) {
        // Discard the "was sleeping" bit because plain CoreLatch has
        // no integrated wakeup mechanism. Wrappers (SpinLatch /
        // CountLatch / LockLatch) override `Latch::set` to wake
        // their associated worker.
        //
        // SAFETY: the trait method's `# Safety` clause forwards
        // the validity-of-`this` precondition to the caller;
        // inner `CoreLatch::set` honors the same contract.
        // @hook-allow:no-let-underscore
        let _ = unsafe { CoreLatch::set(this) };
    }
}

/// Wake-capable latch wrapper: holds a `CoreLatch` plus an
/// `Arc<Parker>` for the worker that is waiting on this latch. When
/// `Latch::set` fires and the prior state was `SLEEPING`, the
/// publisher unparks the parker, releasing the parked worker.
///
/// This is the missing piece that lets the join wait loop in
/// `arena::join_in_worker` actually sleep on the latch instead of
/// hot-spinning on `yield_now()`. Without a wake-capable latch, the
/// wait-loop worker burns CPU continuously while the thief executes
/// its stolen right-half, starving productive CPU from peers and
/// the main thread.
///
/// Lifetime + invalidation: per the `Latch::set` `# Safety` clause,
/// `set` reads every field BEFORE the publishing CoreLatch store so
/// the latch may be deallocated by the awakened thread the moment
/// `is_set` returns true. The `parker.clone()` bumps the parker's
/// Arc refcount via a heap-allocated control block whose lifetime
/// is independent of the latch's stack frame.
pub struct SpinLatch {
    /// State machine underlying this wake-capable wrapper. Exposed
    /// so callers can route the existing `Latch::set` /
    /// `is_set` API through the inner core without duplicating
    /// every method.
    pub core: CoreLatch,
    /// Parker for the worker that is sleeping (or is about to
    /// sleep) on this latch. `Latch::set` clones this Arc BEFORE
    /// the publishing CoreLatch store so the parker remains valid
    /// even after the awakened worker deallocates the latch's
    /// stack frame.
    pub parker: std::sync::Arc<crate::sched::sleep::Parker>,
}

impl SpinLatch {
    /// Construct a fresh wake-capable latch attached to `parker`.
    #[inline]
    pub fn new(parker: std::sync::Arc<crate::sched::sleep::Parker>) -> Self {
        Self {
            core: CoreLatch::new(),
            parker,
        }
    }

    /// Forwarded test for is_set on the underlying CoreLatch.
    #[inline]
    pub fn is_set(&self) -> bool {
        self.core.is_set()
    }

    /// Forwarded sleep handshake: first transition (`UNSET ->
    /// SLEEPY`).
    #[inline]
    pub fn get_sleepy(&self) -> bool {
        self.core.get_sleepy()
    }

    /// Forwarded sleep handshake: second transition (`SLEEPY ->
    /// SLEEPING`).
    #[inline]
    pub fn fall_asleep(&self) -> bool {
        self.core.fall_asleep()
    }

    /// Forwarded post-wake reset (`SLEEPING -> UNSET`).
    #[inline]
    pub fn wake_up(&self) {
        self.core.wake_up();
    }
}

impl Latch for SpinLatch {
    #[inline]
    unsafe fn set(this: *const Self) {
        // SAFETY: read the parker Arc BEFORE the publishing
        // CoreLatch::set store. The parker Arc lives in a heap-
        // allocated control block whose lifetime is independent
        // of the latch's owning stack frame, so the cloned Arc
        // remains valid even after the parked worker observes
        // `SET` and deallocates `*this`.
        let parker = unsafe { (*this).parker.clone() };
        // SAFETY: trait method's `# Safety` clause forwards the
        // validity-of-`this` precondition; inner CoreLatch::set
        // honors the publish-then-invalidate contract.
        let was_sleeping = unsafe { CoreLatch::set(&(*this).core) };
        if was_sleeping {
            // Worker was parked on its Parker waiting for this
            // latch; wake it so the wait loop's predicate observes
            // `is_set == true` and returns from the join.
            parker.unpark();
        }
    }
}

/// The latch of a join's right half: the [`CoreLatch`] states and the
/// address of the forking worker's join parker in one word, so the thief
/// that sets it can wake that worker when it parked to wait.
///
/// A [`crate::sched::sleep::Parker`] is 64-byte aligned, so its address
/// leaves the low two bits free for the state. The latch is one pointer
/// wide, and a set is one swap, as a [`CoreLatch`]'s is.
///
/// The parker is held by address, not by `Arc`. It is the waiting
/// worker's own and lives in that worker's context for the worker's
/// whole life, which outlasts every join the worker is inside.
pub struct JoinLatch {
    /// The parker's address with the latch state in the low two bits.
    word: AtomicUsize,
}

/// The bits of [`JoinLatch`]'s word that hold the state.
const STATE_BITS: usize = 0b11;

impl JoinLatch {
    /// A fresh latch whose set wakes `parker` when its owner parked on it.
    /// `parker` must outlive every set of this latch.
    #[inline]
    pub fn new(parker: &crate::sched::sleep::Parker) -> Self {
        let address = core::ptr::from_ref(parker) as usize;
        debug_assert_eq!(address & STATE_BITS, 0, "a Parker is 64-byte aligned");
        Self {
            word: AtomicUsize::new(address | usize::from(UNSET)),
        }
    }

    /// The parker's address, which no transition changes.
    #[inline]
    fn address(&self) -> usize {
        self.word.load(Ordering::Relaxed) & !STATE_BITS
    }

    /// Moves the state from `from` to `to`, as [`CoreLatch`]'s handshake
    /// transitions do.
    #[inline]
    fn transition(&self, from: u8, to: u8) -> bool {
        let address = self.address();
        self.word
            .compare_exchange(
                address | usize::from(from),
                address | usize::from(to),
                Ordering::SeqCst,
                Ordering::Relaxed,
            )
            .is_ok()
    }

    /// Whether the latch has been set, Acquire-ordered as
    /// [`CoreLatch::is_set`] is.
    #[inline]
    pub fn is_set(&self) -> bool {
        self.word.load(Ordering::Acquire) & STATE_BITS == usize::from(SET)
    }

    /// First phase of the sleep handshake, as [`CoreLatch::get_sleepy`].
    #[inline]
    pub fn get_sleepy(&self) -> bool {
        self.transition(UNSET, SLEEPY)
    }

    /// Second phase of the sleep handshake, as [`CoreLatch::fall_asleep`].
    #[inline]
    pub fn fall_asleep(&self) -> bool {
        self.transition(SLEEPY, SLEEPING)
    }

    /// Reverts a wake that did not observe the set, as
    /// [`CoreLatch::wake_up`].
    #[inline]
    pub fn wake_up(&self) {
        if !self.is_set() {
            self.transition(SLEEPING, UNSET);
        }
    }

    /// The parker this latch wakes.
    #[inline]
    pub fn parker(&self) -> &crate::sched::sleep::Parker {
        // SAFETY: the constructor's contract keeps the parker alive for
        // as long as the latch is in use, and no transition changes the
        // address bits.
        unsafe { &*(self.address() as *const crate::sched::sleep::Parker) }
    }
}

impl Latch for JoinLatch {
    #[inline]
    unsafe fn set(this: *const Self) {
        // SAFETY: the trait method's `# Safety` clause forwards the
        // validity-of-`this` precondition. The address is read before the
        // publishing swap and nothing of `*this` is touched after it.
        let address = unsafe { (*this).address() };
        // SAFETY: as above.
        let old = unsafe {
            (*this)
                .word
                .swap(address | usize::from(SET), Ordering::AcqRel)
        };
        if old & STATE_BITS == usize::from(SLEEPING) {
            // SAFETY: the parker outlives the latch.
            unsafe { &*(address as *const crate::sched::sleep::Parker) }.unpark();
        }
    }
}

/// N-participant wake-capable latch. The inner `CoreLatch` only
/// transitions to `SET` when a counter reaches zero; each
/// `Latch::set` call decrements the counter. The publisher whose
/// decrement reaches zero (and only that publisher) is responsible
/// for unparking the parked waiter.
///
/// Designed for the SIMC `cooperative_join_n` cooperative-vector
/// dispatch: N participating workers each call `Latch::set` when
/// they complete their slice; the owner that submitted the
/// cooperative dispatch is the parked waiter. Without an integrated
/// count, callers would track the N-completion gate manually with
/// an external AtomicUsize and a separate condvar pair, which the
/// existing cooperative.rs path does. This struct centralizes the
/// pattern so the existing sites can adopt it.
///
/// Lifetime + invalidation: the parker Arc is cloned BEFORE the
/// CoreLatch publishing store on the final decrement, same
/// discipline as SpinLatch.
pub struct CountLatch {
    /// Outstanding count of `Latch::set` calls remaining before
    /// the inner CoreLatch transitions to SET. Decremented by each
    /// publisher; the decrementer that observes the new value 0
    /// performs the CoreLatch swap + unpark.
    count: std::sync::atomic::AtomicUsize,
    /// State machine underlying this counted wrapper.
    core: CoreLatch,
    /// Parker for the worker awaiting the all-set transition.
    /// Cloned before publish, same as SpinLatch.
    parker: std::sync::Arc<crate::sched::sleep::Parker>,
}

impl CountLatch {
    /// Construct a fresh count latch for `n` participants.
    /// Panics if `n == 0` (a latch that's already-set from
    /// construction has no callers).
    #[inline]
    pub fn new(n: usize, parker: std::sync::Arc<crate::sched::sleep::Parker>) -> Self {
        assert!(n > 0, "CountLatch requires at least 1 participant");
        Self {
            count: std::sync::atomic::AtomicUsize::new(n),
            core: CoreLatch::new(),
            parker,
        }
    }

    /// Test whether the latch has transitioned to SET (all N
    /// participants have called Latch::set).
    #[inline]
    pub fn is_set(&self) -> bool {
        self.core.is_set()
    }

    /// Sleep handshake first transition (UNSET -> SLEEPY).
    /// Mirrors SpinLatch; forwarded to the inner CoreLatch.
    #[inline]
    pub fn get_sleepy(&self) -> bool {
        self.core.get_sleepy()
    }

    /// Sleep handshake second transition (SLEEPY -> SLEEPING).
    /// Mirrors SpinLatch; forwarded to the inner CoreLatch.
    #[inline]
    pub fn fall_asleep(&self) -> bool {
        self.core.fall_asleep()
    }

    /// Post-wake reset (SLEEPING -> UNSET). Mirrors SpinLatch;
    /// forwarded to the inner CoreLatch.
    #[inline]
    pub fn wake_up(&self) {
        self.core.wake_up();
    }

    /// Read the outstanding count (debug / observability).
    #[inline]
    pub fn outstanding(&self) -> usize {
        self.count.load(std::sync::atomic::Ordering::Acquire)
    }
}

impl Latch for CountLatch {
    #[inline]
    unsafe fn set(this: *const Self) {
        // SAFETY: read both the count cell and the parker BEFORE
        // the final-decrement publishing CoreLatch store. After
        // that store, *this is allowed to be deallocated by the
        // awakened waiter.
        let prior = unsafe {
            (*this).count.fetch_sub(1, std::sync::atomic::Ordering::AcqRel)
        };
        debug_assert!(prior > 0, "CountLatch::set called more times than the construction count");
        if prior > 1 {
            // Not the last decrementer; nothing more to publish.
            return;
        }
        // We are the final decrementer. Clone the parker BEFORE
        // the CoreLatch swap so we still have a valid reference
        // even after the awakened waiter deallocates *this.
        let parker = unsafe { (*this).parker.clone() };
        // SAFETY: forwarded by the trait method's contract; inner
        // CoreLatch::set honors the publish-then-invalidate
        // discipline.
        let was_sleeping = unsafe { CoreLatch::set(&(*this).core) };
        if was_sleeping {
            parker.unpark();
        }
    }
}

/// Cross-thread mutex-free wake-capable latch. Used when the
/// waiter is OUTSIDE the worker pool (the main thread calling
/// `arena::join` from outside, or a foreign-language caller that
/// doesn't own a Parker). The waiter calls `wait()` which uses
/// `thread::park` to block on the kernel-native futex without
/// going through Mutex+Condvar; the setter calls `unpark` on the
/// stored Thread handle after publishing the AtomicBool flag.
///
/// Avoids a Mutex+Condvar pairing: each Mutex lock/unlock on
/// Linux costs an uncontended atomic CAS (fast) plus, on
/// contention, a futex syscall, and each Condvar wait/notify is a
/// futex syscall. The mutex-free design uses just one atomic
/// store + one unpark syscall on the setter side and one atomic
/// load + one park syscall on the waiter side - half the syscalls
/// per side compared to the mutex+condvar pattern. Mirrors
/// rayon's `LockLatch` lock-free shape.
pub struct LockLatch {
    /// Fast-path state. The waiter checks this before parking;
    /// the setter publishes Release-true BEFORE the unpark so a
    /// post-publish waiter observes true on its is_set check and
    /// skips the park syscall entirely.
    flag: std::sync::atomic::AtomicBool,
    /// Handle of the parked waiter thread, published exactly
    /// once by `wait` BEFORE parking. The setter clones it out
    /// before the publishing store on `flag` so the parker
    /// remains valid even if the awakened waiter deallocates
    /// `*this`.
    waiter: std::sync::OnceLock<std::thread::Thread>,
}

impl Default for LockLatch {
    fn default() -> Self {
        Self::new()
    }
}

impl LockLatch {
    /// Construct a fresh cross-thread latch in the UNSET state.
    #[inline]
    pub fn new() -> Self {
        Self {
            flag: std::sync::atomic::AtomicBool::new(false),
            waiter: std::sync::OnceLock::new(),
        }
    }

    /// Block the calling thread until `Latch::set` is called.
    /// Idempotent and re-entrant: returns immediately if already
    /// set when called.
    pub fn wait(&self) {
        if locklatch_diagnose_enabled() {
            notice!("[locklatch] wait enter tid={:?}", std::thread::current().id());
        }
        // Fast path: if the latch is already set, return without
        // touching the OnceLock or any park syscalls.
        if self.flag.load(std::sync::atomic::Ordering::Acquire) {
            if locklatch_diagnose_enabled() {
                notice!("[locklatch] wait exit (fast)  tid={:?}", std::thread::current().id());
            }
            return;
        }
        // Slow path: publish our Thread handle so the setter
        // can unpark us. The OnceLock can only be set once per
        // LockLatch lifetime, which matches the latch's one-
        // waiter contract. The error path on a duplicate set
        // means a second wait() call concurrent with the first -
        // not supported; LockLatch is a single-waiter primitive.
        // Discard returns Result<(), Thread> on duplicate set;
        // any wait() call after the first wait() of the same
        // LockLatch is a contract violation, but we tolerate it
        // by falling through to the park-retry loop below where
        // the flag re-check on every wake still produces correct
        // termination.
        let our_handle = std::thread::current();
        drop(self.waiter.set(our_handle));
        // Race-recovery re-check: the setter might have fired
        // between our fast-path check and our handle publish.
        // If so, the setter would observe no waiter handle and
        // not call unpark; we must observe the flag here so we
        // do not park forever.
        if self.flag.load(std::sync::atomic::Ordering::Acquire) {
            if locklatch_diagnose_enabled() {
                notice!("[locklatch] wait exit (race)  tid={:?}", std::thread::current().id());
            }
            return;
        }
        // Park-retry loop: thread::park can return spuriously, so
        // we re-check the flag on every wake. The setter's unpark
        // is delivered as a permit to the saved Thread handle, so
        // any number of pre-park unparks (e.g. from a race where
        // setter unparks before we reach park) are absorbed and
        // make the first park return immediately.
        while !self.flag.load(std::sync::atomic::Ordering::Acquire) {
            std::thread::park();
        }
        if locklatch_diagnose_enabled() {
            notice!("[locklatch] wait exit  tid={:?}", std::thread::current().id());
        }
    }

    /// Test whether the latch is SET without blocking. Single
    /// Acquire load on the fast-path AtomicBool; does not take
    /// the mutex. Callers spinning on `is_set` before falling
    /// through to `wait` pay no syscall per spin iteration.
    pub fn is_set(&self) -> bool {
        self.flag.load(std::sync::atomic::Ordering::Acquire)
    }

    /// Wait for the latch through the ladder a foreign caller wants:
    /// `spin_cycles` of `PAUSE` first, then [`Self::wait`].
    ///
    /// With [`crate::sched::levers::latch_monitor`] on and a host that
    /// has a monitor wait, the ladder gains a middle rung: a short
    /// spin floor, then bounded waits on the flag's own cache line,
    /// then the park. The three rungs are one mechanism rather than
    /// three choices. A `PAUSE` spin is the fastest wake there is,
    /// because it never stopped looking, and the most expensive way to
    /// be idle, because it issues into the pipeline the whole time; a
    /// monitor wait ends on the same store and issues nothing, so the
    /// hardware thread's sibling gets the core's pipelines; the park
    /// gives the logical processor back and costs a syscall to wake.
    /// Which rung a wait ends on is decided by how long it turns out
    /// to be, which is not knowable when it starts.
    ///
    /// Returns without waiting once the flag reads set, on any rung.
    pub fn wait_spin_then_monitor(&self, spin_cycles: usize) {
        // Decided once, before either ladder starts. A host with no
        // monitor, or one whose monitor has been found not to hold,
        // takes the spin the caller asked for and the park after it,
        // which is what it would take with the lever off; deciding
        // this per round instead would cut that spin to the floor and
        // make the lever two changes rather than one.
        let budget_cycles = crate::sched::par_iter::installed_dispatch_cost_ns()
            .saturating_mul(crate::sched::par_iter::tsc_per_ns_16())
            / 16;
        let use_monitor = crate::sched::levers::latch_monitor()
            && budget_cycles > 0
            && crate::sched::sleep::monitor_wait_available();

        if !use_monitor {
            for _ in 0..spin_cycles {
                if self.is_set() {
                    return;
                }
                std::hint::spin_loop();
            }
            self.wait();
            return;
        }

        // The floor, sized as the mailbox thief's is: long enough that
        // a set already in flight lands here, short enough that the
        // pipeline is not held for a wait that was never going to be
        // short. It is also timed, and that timing is what sizes the
        // rung below it: a PAUSE costs a different number of cycles on
        // every part, so the only way to spend the same wall time the
        // other arm spends is to measure this host's PAUSE here, on
        // polls that were going to run anyway.
        let floor_start = crate::sched::sleep::cycles_now();
        for _ in 0..MONITOR_SPIN_FLOOR {
            if self.is_set() {
                return;
            }
            std::hint::spin_loop();
        }
        let per_poll = crate::sched::sleep::cycles_now().saturating_sub(floor_start)
            / MONITOR_SPIN_FLOOR as u64;
        // A floor the scheduler interrupted measures the interruption
        // rather than a PAUSE, and sizing the rung from it would hold
        // this thread for far longer than the spin it stands in for. A
        // poll costs 20 to 140 cycles on the parts here, so a reading
        // past this ceiling is not one, and the wait takes the spin the
        // other arm takes instead of a rung it cannot size.
        if per_poll == 0 || per_poll > MAX_MEASURED_POLL_CYCLES {
            for _ in MONITOR_SPIN_FLOOR..spin_cycles {
                if self.is_set() {
                    return;
                }
                std::hint::spin_loop();
            }
            self.wait();
            return;
        }
        // The middle rung ends when the spin it replaces would have
        // ended, so both arms park at the same moment and differ only
        // in what this thread did while waiting.
        //
        // Each wait is bounded by what remains of the rung, which makes
        // the common case one arming. A store to the line ends a long
        // wait exactly as fast as a short one: the monitor is armed
        // before the flag is read, and a store landing between the
        // arming and the wait leaves the monitor triggered, so the wait
        // returns at once and no wake is lost. A bound shorter than the
        // rung therefore buys no promptness, and costs an arming for
        // every width of it the wait turns out to span. The rung still
        // bounds each wait, so a monitor cleared without a store costs
        // at most the rest of a span this thread was spending on the
        // flag anyway.
        let ladder_cycles =
            (spin_cycles.saturating_sub(MONITOR_SPIN_FLOOR) as u64).saturating_mul(per_poll);
        let line = (&raw const self.flag).cast::<u8>();
        crate::sched::sleep::note_latch_monitor_wait(false);
        let ladder_start = crate::sched::sleep::cycles_now();
        loop {
            // The flag first, because it is a load and the clock is
            // not, and this is the exit every wait that ends well
            // takes.
            if self.is_set() {
                return;
            }
            let spent = crate::sched::sleep::cycles_now().saturating_sub(ladder_start);
            let left = ladder_cycles.saturating_sub(spent);
            if left == 0 {
                break;
            }
            crate::sched::sleep::note_latch_monitor_arm();
            // SAFETY: `line` points at this latch's own flag, which
            // lives as long as `self`, and the wait is issued only
            // where CPUID reported the pair.
            let waited =
                unsafe { crate::sched::sleep::monitor_wait_once(line, left, || self.is_set()) };
            if !waited {
                break;
            }
        }
        self.wait();
    }
}

/// `PAUSE` polls a monitor-waiting latch spins before its first
/// monitor wait. 512, as the mailbox thief's floor is, because both
/// are covering the same thing: a store already on its way. A
/// shared-memory backend's result wait takes the same floor.
pub(crate) const MONITOR_SPIN_FLOOR: usize = 512;

/// Cycles per poll above which the floor's timing is read as an
/// interruption rather than as this host's `PAUSE`. A poll costs 20 to
/// 140 cycles on the parts this runs on, so anything past four times
/// the widest of those is something else.
pub(crate) const MAX_MEASURED_POLL_CYCLES: u64 = 512;

/// Diagnostic gate for LockLatch.wait() entry/exit logging. Reads
/// the env var once via OnceLock so the hot wait path pays just a
/// cached Relaxed load per call. Set FLYNNEL_LOCKLATCH_DIAGNOSE=1
/// to enable; default off.
fn locklatch_diagnose_enabled() -> bool {
    static CACHE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *CACHE.get_or_init(|| {
        std::env::var("FLYNNEL_LOCKLATCH_DIAGNOSE")
            .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
            .unwrap_or(false)
    })
}

impl Latch for LockLatch {
    #[inline]
    unsafe fn set(this: *const Self) {
        // SAFETY: read the waiter handle BEFORE the publishing
        // flag.store. After the store, the waiter may observe
        // is_set=true (in its fast-path or race-recovery check)
        // and deallocate *this. The Thread handle is itself an
        // Arc<Inner> heap-allocated cell; cloning it bumps the
        // refcount on the inner before any race window opens, so
        // the handle remains valid for the post-store unpark even
        // after *this is invalidated.
        let waiter_opt = unsafe { (*this).waiter.get().cloned() };
        // Publishing store. Release ordering pairs with the
        // waiter's Acquire load on the flag.
        unsafe { (*this).flag.store(true, std::sync::atomic::Ordering::Release) };
        // *this may now be invalidated; use waiter_opt only.
        if let Some(handle) = waiter_opt {
            handle.unpark();
        }
        // If waiter_opt is None, the waiter hasn't yet published
        // its handle (race: waiter passed its fast-path check but
        // hasn't set the OnceLock yet). The waiter's post-publish
        // re-check of the flag will observe true and return
        // immediately without parking.
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use std::sync::atomic::AtomicUsize;
    use std::thread;
    use std::time::{Duration, Instant};

    #[test]
    fn new_latch_is_unset() {
        let l = CoreLatch::new();
        assert!(!l.is_set());
    }

    #[test]
    fn set_marks_set() {
        let l = CoreLatch::new();
        unsafe { Latch::set(&l) };
        assert!(l.is_set());
    }

    #[test]
    fn spin_latch_wakes_parked_thread() {
        // E2E test of the SpinLatch wake-capable wrapper. The Parker
        // is constructed on the waiter thread (captures
        // thread::current() at construction), then handed to the
        // setter thread via a channel along with the latch. This
        // mirrors the real flynnel usage where each worker's parker
        // is owned by that worker, and a thief on a different
        // thread calls Latch::set.
        //
        // Without the parker.unpark() in SpinLatch::set, the parked
        // waiter would hang until a spurious wake or shutdown.
        use std::sync::mpsc;
        let (tx, rx) = mpsc::channel::<Arc<SpinLatch>>();

        let waiter = thread::spawn(move || {
            // Waiter owns the Parker; capture its own thread handle
            // so SpinLatch::set's unpark targets the waiting thread.
            let parker = Arc::new(crate::sched::sleep::Parker::new(0));
            let latch = Arc::new(SpinLatch::new(parker));
            // Hand a clone of the latch to the setter thread.
            tx.send(latch.clone()).unwrap();
            // Sleep handshake on this thread (the parker's owner).
            assert!(latch.get_sleepy(), "fresh latch must accept get_sleepy");
            assert!(!latch.is_set(), "no setter has run yet");
            assert!(
                latch.fall_asleep(),
                "no setter raced us between get_sleepy and fall_asleep"
            );
            // Park until latch set; predicate re-checks on wake.
            let _unparked: bool = latch.parker.park_until(|| latch.is_set());
            latch.wake_up();
            assert!(latch.is_set(), "must observe SET after wake");
        });

        // Setter on the test main thread: receive the latch and
        // publish SET after a delay long enough for the waiter to
        // reach the actual park syscall.
        let latch = rx.recv().expect("waiter must send latch");
        thread::sleep(Duration::from_millis(50));
        unsafe { Latch::set(&*latch) };

        // Waiter must complete within a generous bound; if it hangs
        // here the unpark from Latch::set never reached the waiter.
        let t0 = Instant::now();
        loop {
            if waiter.is_finished() {
                waiter.join().unwrap();
                break;
            }
            if t0.elapsed() > Duration::from_secs(5) {
                panic!("waiter did not wake within 5s after Latch::set");
            }
            thread::sleep(Duration::from_millis(10));
        }
    }

    #[test]
    fn join_latch_wakes_its_parked_owner() {
        // The owner builds its parker and the latch on its own thread
        // and parks through the handshake; the set, from another thread,
        // must end the park. The parker is leaked, as a worker's join
        // parker outlives every latch that names it. A wake that is not
        // the set parks again, so only the set's unpark can let the
        // owner finish inside the bound.
        use std::sync::mpsc;
        let (tx, rx) = mpsc::channel::<Arc<JoinLatch>>();

        let waiter = thread::spawn(move || {
            let parker: &'static crate::sched::sleep::Parker =
                Box::leak(Box::new(crate::sched::sleep::Parker::with_strategy(
                    0,
                    crate::sched::sleep::WaitStrategy::StdPark,
                )));
            let latch = Arc::new(JoinLatch::new(parker));
            tx.send(latch.clone()).unwrap();
            while !latch.is_set() {
                if latch.get_sleepy() && latch.fall_asleep() {
                    let _unparked: bool = latch.parker().park_until(|| latch.is_set());
                }
                latch.wake_up();
            }
        });

        let latch = rx.recv().expect("waiter must send latch");
        thread::sleep(Duration::from_millis(50));
        unsafe { Latch::set(&*latch) };

        let t0 = Instant::now();
        loop {
            if waiter.is_finished() {
                waiter.join().unwrap();
                break;
            }
            if t0.elapsed() > Duration::from_secs(5) {
                panic!("owner did not wake within 5s after the JoinLatch was set");
            }
            thread::sleep(Duration::from_millis(10));
        }
    }

    #[test]
    fn join_latch_set_before_any_park_refuses_the_handshake() {
        let parker = crate::sched::sleep::Parker::with_strategy(
            0,
            crate::sched::sleep::WaitStrategy::StdPark,
        );
        let latch = JoinLatch::new(&parker);
        unsafe { Latch::set(&latch) };
        assert!(latch.is_set());
        assert!(
            !latch.get_sleepy(),
            "a set latch must not let its owner park"
        );
    }

    #[test]
    fn count_latch_only_sets_on_final_decrement() {
        // Build a 3-participant count latch on a dummy parker.
        // First two decrements must leave the inner state unset;
        // third decrement transitions to SET.
        let parker = Arc::new(crate::sched::sleep::Parker::new(0));
        let latch = CountLatch::new(3, parker);
        assert_eq!(latch.outstanding(), 3);
        assert!(!latch.is_set());
        unsafe { Latch::set(&latch) };
        assert_eq!(latch.outstanding(), 2);
        assert!(!latch.is_set(), "must not set until final decrement");
        unsafe { Latch::set(&latch) };
        assert_eq!(latch.outstanding(), 1);
        assert!(!latch.is_set(), "must not set until final decrement");
        unsafe { Latch::set(&latch) };
        assert_eq!(latch.outstanding(), 0);
        assert!(latch.is_set(), "final decrement must transition to SET");
    }

    #[test]
    fn count_latch_wakes_parked_thread_on_final_set() {
        // E2E: N setters across multiple threads + one waiter on
        // its own Parker. Only the final decrement unparks.
        use std::sync::mpsc;
        let (tx, rx) = mpsc::channel::<Arc<CountLatch>>();
        let n = 4usize;

        let waiter = thread::spawn(move || {
            let parker = Arc::new(crate::sched::sleep::Parker::new(0));
            let latch = Arc::new(CountLatch::new(n, parker));
            tx.send(latch.clone()).unwrap();
            assert!(latch.get_sleepy());
            assert!(latch.fall_asleep());
            let _unparked: bool = latch.parker.park_until(|| latch.is_set());
            latch.wake_up();
            assert!(latch.is_set(), "must observe SET after final decrement");
        });

        let latch = rx.recv().expect("waiter sent latch");
        thread::sleep(Duration::from_millis(20));
        let mut setters = Vec::new();
        for _ in 0..n {
            let l2 = latch.clone();
            setters.push(thread::spawn(move || unsafe { Latch::set(&*l2) }));
        }
        for s in setters {
            s.join().unwrap();
        }

        let t0 = Instant::now();
        loop {
            if waiter.is_finished() {
                waiter.join().unwrap();
                break;
            }
            if t0.elapsed() > Duration::from_secs(5) {
                panic!("waiter did not wake within 5s after N decrements");
            }
            thread::sleep(Duration::from_millis(10));
        }
    }

    #[test]
    fn lock_latch_wakes_cross_thread_waiter() {
        // External-thread pattern: main thread waits via wait();
        // worker thread calls Latch::set; main thread unblocks.
        let latch = Arc::new(LockLatch::new());
        assert!(!latch.is_set());

        let l2 = latch.clone();
        let setter = thread::spawn(move || {
            thread::sleep(Duration::from_millis(30));
            unsafe { Latch::set(&*l2) };
        });

        let t0 = Instant::now();
        latch.wait();
        let elapsed = t0.elapsed();
        assert!(latch.is_set());
        assert!(
            elapsed >= Duration::from_millis(20),
            "wait must have actually blocked (got {elapsed:?})"
        );
        assert!(
            elapsed < Duration::from_secs(5),
            "wait must wake within 5s (got {elapsed:?})"
        );
        setter.join().unwrap();
    }

    #[test]
    fn lock_latch_wait_returns_immediately_when_already_set() {
        // Idempotency: a wait() on an already-set LockLatch
        // returns without blocking.
        let latch = LockLatch::new();
        unsafe { Latch::set(&latch) };
        let t0 = Instant::now();
        latch.wait();
        assert!(
            t0.elapsed() < Duration::from_millis(50),
            "wait on already-set latch must return immediately"
        );
        assert!(latch.is_set());
    }

    #[test]
    fn spin_latch_already_set_does_not_park() {
        // Edge case: latch is already SET when waiter attempts the
        // handshake. get_sleepy must fail because the state is SET,
        // not unset. The waiter must not park.
        let parker = Arc::new(crate::sched::sleep::Parker::new(0));
        let latch = SpinLatch::new(parker);
        unsafe { Latch::set(&latch) };
        assert!(latch.is_set());
        // get_sleepy CAS UNSET->SLEEPY fails when state is SET.
        assert!(!latch.get_sleepy(), "get_sleepy must fail on already-set latch");
    }

    #[test]
    fn get_sleepy_succeeds_then_fails_after_set() {
        let l = CoreLatch::new();
        assert!(l.get_sleepy(), "UNSET -> SLEEPY should succeed");
        // Second call returns false because state is no longer UNSET.
        assert!(!l.get_sleepy(), "SLEEPY -> SLEEPY should fail");
        unsafe { Latch::set(&l) };
        // Now the state is SET, so get_sleepy should still fail.
        assert!(!l.get_sleepy(), "SET -> SLEEPY should fail");
    }

    #[test]
    fn fall_asleep_requires_sleepy_first() {
        let l = CoreLatch::new();
        // `UNSET` -> `SLEEPING` is not a valid direct transition.
        assert!(!l.fall_asleep(), "UNSET -> SLEEPING must fail");
        assert!(l.get_sleepy());
        assert!(l.fall_asleep(), "SLEEPY -> SLEEPING should succeed");
        // Second fall_asleep no-ops because state is no longer SLEEPY.
        assert!(!l.fall_asleep());
    }

    #[test]
    fn set_returns_true_when_prior_was_sleeping() {
        let l = CoreLatch::new();
        assert!(l.get_sleepy());
        assert!(l.fall_asleep());
        // Direct call to the unsafe setter so we can observe the
        // return value (the Latch::set trait impl discards it).
        let was_sleeping = unsafe { CoreLatch::set(&l) };
        assert!(was_sleeping, "set must return true when prior was SLEEPING");
    }

    #[test]
    fn set_returns_false_when_prior_was_unset() {
        let l = CoreLatch::new();
        let was_sleeping = unsafe { CoreLatch::set(&l) };
        assert!(!was_sleeping, "set must return false when prior was UNSET");
    }

    #[test]
    fn set_returns_false_when_prior_was_sleepy() {
        let l = CoreLatch::new();
        assert!(l.get_sleepy());
        let was_sleeping = unsafe { CoreLatch::set(&l) };
        assert!(!was_sleeping, "set must return false when prior was SLEEPY");
        // Publisher dodged the park: caller never reached fall_asleep.
    }

    #[test]
    fn wake_up_reverts_sleeping_to_unset() {
        let l = CoreLatch::new();
        assert!(l.get_sleepy());
        assert!(l.fall_asleep());
        // Simulate a spurious wakeup: thread observed work without
        // the latch being set. wake_up reverts SLEEPING -> UNSET so
        // it can re-enter the work search.
        l.wake_up();
        assert!(!l.is_set());
        // We can now get_sleepy again because state is UNSET.
        assert!(l.get_sleepy());
    }

    #[test]
    fn wake_up_after_set_is_noop() {
        let l = CoreLatch::new();
        assert!(l.get_sleepy());
        assert!(l.fall_asleep());
        unsafe { Latch::set(&l) };
        // wake_up sees is_set() == true and exits early.
        l.wake_up();
        assert!(l.is_set(), "set state must not be reverted by wake_up");
    }

    #[test]
    fn concurrent_get_sleepy_serializes_to_one_winner() {
        // Two threads racing on get_sleepy: exactly one should win.
        let l = Arc::new(CoreLatch::new());
        let wins = Arc::new(AtomicUsize::new(0));
        let mut handles = Vec::new();
        for _ in 0..8 {
            let l = Arc::clone(&l);
            let wins = Arc::clone(&wins);
            handles.push(thread::spawn(move || {
                if l.get_sleepy() {
                    wins.fetch_add(1, Ordering::SeqCst);
                }
            }));
        }
        for h in handles {
            h.join().unwrap();
        }
        assert_eq!(wins.load(Ordering::SeqCst), 1,
            "exactly one thread should win the UNSET -> SLEEPY CAS");
    }

    #[test]
    fn set_synchronizes_publisher_and_observer() {
        // Acquire-Release sanity check: data written by the
        // publisher BEFORE set must be visible to the observer
        // after is_set returns true.
        let l = Arc::new(CoreLatch::new());
        let payload: Arc<AtomicUsize> = Arc::new(AtomicUsize::new(0));

        let l_pub = Arc::clone(&l);
        let payload_pub = Arc::clone(&payload);
        let pub_handle = thread::spawn(move || {
            payload_pub.store(0xDEAD_BEEF, Ordering::Relaxed);
            unsafe { Latch::set(&*l_pub) };
        });

        let l_obs = Arc::clone(&l);
        let payload_obs = Arc::clone(&payload);
        let obs_handle = thread::spawn(move || {
            let deadline = Instant::now() + Duration::from_secs(2);
            while !l_obs.is_set() {
                if Instant::now() > deadline {
                    panic!("observer never saw set within 2s");
                }
                std::thread::yield_now();
            }
            // After is_set returns true, the payload store must be
            // visible. Acquire ordering on is_set + Relaxed store on
            // the publisher works because the AcqRel swap in set
            // provides the release fence.
            payload_obs.load(Ordering::Relaxed)
        });

        pub_handle.join().unwrap();
        let observed = obs_handle.join().unwrap();
        assert_eq!(observed, 0xDEAD_BEEF,
            "observer must see publisher's writes after is_set");
    }
}