extern crate hwloc;
extern crate libc;
use hwloc::{Topology, ObjectType, CPUBIND_THREAD, CpuSet};
use std::thread;
use std::sync::{Arc, Mutex};
fn main() {
let topo = Arc::new(Mutex::new(Topology::new()));
let num_cores = {
let topo_rc = topo.clone();
let topo_locked = topo_rc.lock().unwrap();
(*topo_locked).objects_with_type(&ObjectType::Core).unwrap().len()
};
println!("Found {} cores.", num_cores);
let handles: Vec<_> = (0..num_cores)
.map(|i| {
let child_topo = topo.clone();
thread::spawn(move || {
let tid = get_thread_id();
let mut locked_topo = child_topo.lock().unwrap();
let before = locked_topo.get_cpubind_for_thread(tid, CPUBIND_THREAD);
let bind_to = cpuset_for_core(&*locked_topo, i);
locked_topo.set_cpubind_for_thread(tid, bind_to, CPUBIND_THREAD).unwrap();
let after = locked_topo.get_cpubind_for_thread(tid, CPUBIND_THREAD);
println!("Thread {}: Before {:?}, After {:?}", i, before, after);
})
})
.collect();
for h in handles {
h.join().unwrap();
}
}
fn cpuset_for_core(topology: &Topology, idx: usize) -> CpuSet {
let cores = (*topology).objects_with_type(&ObjectType::Core).unwrap();
match cores.get(idx) {
Some(val) => val.cpuset().unwrap(),
None => panic!("No Core found with id {}", idx),
}
}
fn get_thread_id() -> libc::pthread_t {
unsafe { libc::pthread_self() }
}