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 Windows core-affinity syscalls.
15
16 use std::io::{Error, Result};
17 use std::os::windows::raw::HANDLE;
18
19 extern "system" {
GetCurrentThread() -> HANDLE20 fn GetCurrentThread() -> HANDLE;
21
SetThreadAffinityMask(hThread: HANDLE, dwThreadAffinityMask: usize) -> usize22 fn SetThreadAffinityMask(hThread: HANDLE, dwThreadAffinityMask: usize) -> usize;
23 }
24
25 /// Sets the current thread's tied core cpu.
26 ///
27 /// # Note
28 /// In order to align with linux, the `cpu` will be +1 in function,
29 /// so we can Use this interface as with linux
30 ///
31 /// # Example
32 ///
33 /// ```no run
34 /// use ylong_runtime::util::core_affinity;
35 ///
36 /// let ret = core_affinity::set_current_affinity(0).is_ok();
37 /// ```
set_current_affinity(cpu: usize) -> Result<()>38 pub fn set_current_affinity(cpu: usize) -> Result<()> {
39 // In Windows, dwThreadAffinityMask is start from 1, so we have to +1 to align
40 // with linux.
41 let cpu = cpu + 1;
42 // If the function succeeds, the return value is the thread's previous affinity
43 // mask. If the function fails, the return value is 0.
44 let res = unsafe {
45 let handle = GetCurrentThread();
46 SetThreadAffinityMask(handle, cpu) as i32
47 };
48 // To be consistent with linux output, the results are processed
49 match res {
50 0 => Err(Error::last_os_error()),
51 _ => Ok(()),
52 }
53 }
54