Skip to main content

aocl_utils/
threads.rs

1//! Thread-pinning helpers from AOCL-Utils.
2//!
3//! These are very thin wrappers around the AOCL routines that take a
4//! list of OS-level thread handles (`pthread_t` on Unix, `HANDLE` on
5//! Windows) and pin them to physical or logical cores. Most callers
6//! collect `pthread_t` / `HANDLE` values from their thread library
7//! (`std::thread::current().handle()`-style accessors via `os`-specific
8//! crates) before invoking these.
9//!
10//! The functions are `unsafe` because passing a thread handle that no
11//! longer refers to a live thread is undefined behavior on the AOCL
12//! side.
13
14use aocl_utils_sys as sys;
15
16/// OS-native thread handle.
17pub type ThreadHandle = sys::pthread_t;
18
19/// Pinning strategy for a list of thread handles.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum PinStrategy {
22    /// Pin each thread to a unique physical core (one thread per core,
23    /// preferring physical core 0, 1, 2, …).
24    Core,
25    /// Pin each thread to a unique logical processor (SMT thread).
26    Logical,
27    /// Spread threads across cores to maximize per-thread cache, mapping
28    /// each thread to a different L3 / NUMA region when possible.
29    Spread,
30}
31
32/// Pin the given thread handles using the chosen strategy.
33///
34/// # Safety
35///
36/// Each entry of `threads` must be a valid OS-level handle to a still-live
37/// thread. Passing a stale handle (e.g. for a thread that has exited or
38/// been detached) is undefined behavior. The slice's length must fit in
39/// a C `size_t`.
40pub unsafe fn pin_threads(strategy: PinStrategy, threads: &mut [ThreadHandle]) {
41    let n = threads.len();
42    let p = threads.as_mut_ptr();
43    match strategy {
44        PinStrategy::Core => unsafe { sys::au_pin_threads_core(p, n) },
45        PinStrategy::Logical => unsafe { sys::au_pin_threads_logical(p, n) },
46        PinStrategy::Spread => unsafe { sys::au_pin_threads_spread(p, n) },
47    }
48}
49
50/// Pin threads with a custom mapping: `affinity_vector[i]` is the logical
51/// processor index thread `i` should bind to.
52///
53/// # Safety
54///
55/// Same as [`pin_threads`]; in addition, the affinity values must
56/// reference logical processors that exist on the host.
57pub unsafe fn pin_threads_custom(threads: &mut [ThreadHandle], affinity_vector: &[i32]) {
58    let n = threads.len();
59    if n == 0 || affinity_vector.is_empty() {
60        return;
61    }
62    unsafe {
63        sys::au_pin_threads_custom(
64            threads.as_mut_ptr(),
65            n,
66            affinity_vector.as_ptr() as *mut std::os::raw::c_int,
67            affinity_vector.len(),
68        );
69    }
70}
71
72#[cfg(all(test, windows))]
73mod tests {
74    use super::*;
75    use std::os::windows::io::AsRawHandle;
76    use std::sync::mpsc;
77
78    #[repr(C)]
79    #[derive(Default)]
80    struct GroupAffinity {
81        mask: usize,
82        group: u16,
83        reserved: [u16; 3],
84    }
85    extern "system" {
86        fn GetThreadGroupAffinity(
87            thread: *mut core::ffi::c_void,
88            affinity: *mut GroupAffinity,
89        ) -> i32;
90    }
91
92    /// Spawn a live thread that waits, run `f` on its handle, and read back the OS affinity mask of that thread.
93    fn pinned_mask(f: impl FnOnce(&mut [ThreadHandle])) -> usize {
94        let (tx, rx) = mpsc::channel::<()>();
95        let th = std::thread::spawn(move || {
96            let _ = rx.recv();
97        });
98        let mut handles = [th.as_raw_handle() as ThreadHandle];
99        f(&mut handles);
100        let mut ga = GroupAffinity::default();
101        let ok = unsafe { GetThreadGroupAffinity(handles[0] as *mut _, &mut ga) };
102        assert_ne!(ok, 0, "GetThreadGroupAffinity failed");
103        tx.send(()).unwrap();
104        th.join().unwrap();
105        ga.mask
106    }
107
108    #[test]
109    fn pin_threads_custom_binds_the_thread_to_the_requested_logical_processor() {
110        // Logical processor 0 -> exactly bit 0 of the affinity mask. Control: an unpinned thread is not bound to one core
111        // (the default mask has more than one bit set on a multi-core host).
112        let unpinned = pinned_mask(|_| {});
113        let pinned = pinned_mask(|h| unsafe { pin_threads_custom(h, &[0]) });
114        assert_eq!(pinned, 1, "affinity mask after pin_threads_custom(&[0])");
115        if std::thread::available_parallelism()
116            .map(|n| n.get())
117            .unwrap_or(1)
118            > 1
119        {
120            assert!(
121                unpinned.count_ones() > 1,
122                "control: unpinned mask {unpinned:#x}"
123            );
124        }
125    }
126
127    #[test]
128    fn pin_threads_core_and_logical_and_spread_leave_a_single_processor_mask() {
129        // Core / Logical / Spread each pin one live thread to a processor of this host: the mask is non-empty, a subset of
130        // the host's processors, and differs from the unpinned mask (control).
131        let unpinned = pinned_mask(|_| {});
132        for strategy in [PinStrategy::Core, PinStrategy::Logical, PinStrategy::Spread] {
133            let m = pinned_mask(|h| unsafe { pin_threads(strategy, h) });
134            assert_ne!(m, 0, "{strategy:?}");
135            assert!(
136                m.count_ones() >= 1 && m.count_ones() <= unpinned.count_ones(),
137                "{strategy:?}: {m:#x} vs {unpinned:#x}"
138            );
139            if std::thread::available_parallelism()
140                .map(|n| n.get())
141                .unwrap_or(1)
142                > 1
143            {
144                assert_ne!(m, unpinned, "{strategy:?} left the thread unpinned");
145            }
146        }
147    }
148}