agentmux_srv_core/backend/
thread_roles.rs1use std::cell::Cell;
14use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
15use std::time::{Duration, Instant};
16
17static STARTED: AtomicUsize = AtomicUsize::new(0);
18static SETTLED: AtomicBool = AtomicBool::new(false);
19
20thread_local! {
21 static WORKER: Cell<bool> = const { Cell::new(false) };
22}
23
24pub fn thread_started() {
26 if !SETTLED.load(Ordering::Acquire) {
27 WORKER.with(|w| w.set(true));
28 }
29 STARTED.fetch_add(1, Ordering::AcqRel);
30}
31
32pub fn settle(workers: usize) {
35 let began = Instant::now();
36 while STARTED.load(Ordering::Acquire) < workers && began.elapsed() < Duration::from_secs(2) {
37 std::thread::yield_now();
38 }
39 SETTLED.store(true, Ordering::Release);
40}
41
42pub fn on_worker() -> bool {
44 WORKER.with(Cell::get)
45}
46
47#[cfg(test)]
48mod tests {
49 use super::*;
50
51 #[test]
52 fn only_the_threads_started_before_the_settle_are_workers() {
53 assert!(!on_worker(), "a plain test thread is no worker");
54 let worker = std::thread::spawn(|| {
55 thread_started();
56 on_worker()
57 })
58 .join()
59 .unwrap();
60 assert!(worker, "a thread the runtime started while it was built is a worker");
61 settle(1);
62 let later = std::thread::spawn(|| {
63 thread_started();
64 on_worker()
65 })
66 .join()
67 .unwrap();
68 assert!(!later, "a thread started after the runtime was built is not");
69 }
70}