1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
pub struct CpuSet(cpu_set_t);
impl Default for CpuSet
{
#[inline(always)]
fn default() -> Self
{
Self(unsafe { zeroed() })
}
}
impl<'a> From<&'a BTreeSet<HyperThread>> for CpuSet
{
#[inline(always)]
fn from(hyper_threads: &BTreeSet<HyperThread>) -> CpuSet
{
let mut cpu_set = Self::default();
for hyper_thread in hyper_threads.iter()
{
cpu_set.set_hyper_thread(*hyper_thread);
}
cpu_set
}
}
impl CpuSet
{
const SizeOfCpuSetT: usize = size_of::<cpu_set_t>();
#[inline(always)]
pub fn set_current_process_affinity(&self) -> io::Result<()>
{
self.set_process_affinity(0)
}
#[inline(always)]
pub fn set_process_affinity(&self, process_identifier: pid_t) -> io::Result<()>
{
#[link(name = "c")]
extern "C"
{
pub(crate) fn sched_setaffinity(tid: pid_t, size: size_t, set: *const cpu_set_t) -> c_int;
}
let result = unsafe { sched_setaffinity(process_identifier, Self::SizeOfCpuSetT, &self.0) };
if result == 0
{
Ok(())
}
else
{
Err(io::Error::from_raw_os_error(result))
}
}
#[cfg(any(target_os = "emscripten", target_os = "fuschia", target_os = "linux", target_env = "uclibc"))]
#[inline(always)]
pub fn set_thread_affinity(&self, thread_identifier: pthread_t) -> io::Result<()>
{
#[link(name = "c")]
extern "C"
{
pub(crate) fn pthread_setaffinity_np(thread: pthread_t, cpusetsize: size_t, cpuset: *const cpu_set_t) -> c_int;
}
let result = unsafe { pthread_setaffinity_np(thread_identifier, Self::SizeOfCpuSetT, &self.0) };
if result == 0
{
Ok(())
}
else
{
Err(io::Error::from_raw_os_error(result))
}
}
#[inline(always)]
pub fn set_current_thread_affinity(&self) -> io::Result<()>
{
self.set_thread_affinity(unsafe { pthread_self() })
}
#[inline(always)]
pub fn set_hyper_thread(&mut self, hyper_thread: HyperThread)
{
unsafe { CPU_SET(hyper_thread.0 as usize, &mut self.0) }
}
#[cfg(any(target_os = "android"))]
#[inline(always)]
fn _set_thread_affinity(&self, thread_identifier: ThreadIdentifier) -> io::Result<()>
{
Ok(())
}
}