extern crate hwloc;
extern crate libc;
#[cfg(target_os = "windows")]
extern crate kernel32;
#[cfg(target_os = "windows")]
extern crate winapi;
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 mut bind_to = cpuset_for_core(&*locked_topo, i);
bind_to.singlify();
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),
}
}
#[cfg(not(target_os = "windows"))]
fn get_thread_id() -> libc::pthread_t {
unsafe { libc::pthread_self() }
}
#[cfg(target_os = "windows")]
fn get_thread_id() -> winapi::winnt::HANDLE {
unsafe { kernel32::GetCurrentThread() }
}