1 // Copyright (c) 2023 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 //! Wraps Linux core-affinity syscalls.
15
16 use std::io::{Error, Result};
17 use std::mem::{size_of, zeroed};
18
19 use libc::{cpu_set_t, sched_setaffinity, CPU_SET};
20
21 /// Sets the tied core cpu of the current thread.
22 ///
23 /// sched_setaffinity function under linux
24 /// # Example
25 ///
26 /// ```no run
27 /// use ylong_runtime::util::core_affinity;
28 ///
29 /// let ret = core_affinity::set_current_affinity(0).is_ok();
30 /// ```
set_current_affinity(cpu: usize) -> Result<()>31 pub fn set_current_affinity(cpu: usize) -> Result<()> {
32 let res: i32 = unsafe {
33 let mut set = new_cpu_set();
34 CPU_SET(cpu, &mut set);
35 sched_setaffinity(0, size_of::<cpu_set_t>(), &set)
36 };
37 match res {
38 0 => Ok(()),
39 _ => Err(Error::last_os_error()),
40 }
41 }
42
43 /// Returns an empty cpu set
new_cpu_set() -> cpu_set_t44 fn new_cpu_set() -> cpu_set_t {
45 unsafe { zeroed::<cpu_set_t>() }
46 }
47