Skip to main content

agentmux_srv_core/backend/
thread_roles.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which of srv's threads are the async runtime's workers.
5//!
6//! A blocking call is a different problem on a worker (the rest of srv's tasks wait for it) than on a thread of the
7//! blocking pool or a thread srv started itself (only that call waits). Tokio gives no way to ask which one a thread
8//! is, but it launches the workers while the runtime is built, before any blocking task can exist: the threads that
9//! start before [`settle`] is called are the workers. `main` hands [`thread_started`] to the runtime's
10//! `on_thread_start` and calls [`settle`] once the runtime is built; anything that never does (a test, a helper
11//! binary) sees no worker.
12
13use 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
24/// Called by each thread the runtime starts, on that thread.
25pub 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
32/// Called once the runtime is built, with its worker count: waits (a short while at most) for that many threads to
33/// have started, then marks every later thread as not a worker.
34pub 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
42/// Whether the calling thread is one of the runtime's workers.
43pub 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}