1use aocl_utils_sys as sys;
15
16pub type ThreadHandle = sys::pthread_t;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum PinStrategy {
22 Core,
25 Logical,
27 Spread,
30}
31
32pub 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
50pub 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 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 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 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}