1use std::mem::zeroed;
2
3use libc::{cpu_set_t, pthread_self, pthread_setaffinity_np, CPU_SET, CPU_ZERO};
4
5pub fn setaffinity_np(cores: &[usize]) {
6 unsafe {
7 let mut set: cpu_set_t = zeroed();
8 CPU_ZERO(&mut set);
9
10 let thread = pthread_self();
11
12 for i in cores {
13 CPU_SET(*i, &mut set);
14 }
15
16 let s = pthread_setaffinity_np(thread, std::mem::size_of::<cpu_set_t>(), &mut set);
17
18 if s != 0 {
19 panic!("bind failed");
20 }
21 }
22}
23
24#[test]
25fn test_bind_core() {
26 fn fib(n: usize) -> usize {
27 if n == 1 || n == 2 {
28 return 1;
29 }
30
31 fib(n - 1) + fib(n - 2)
32 }
33
34 setaffinity_np(&[1]);
35
36 let n = fib(48);
37 println!("{n}")
38}