cpu_utils/
pinning.rs

1/*
2 * Copyright 2024 Fluence DAO
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use ccp_core_affinity::CoreId;
18
19use crate::LogicalCoreId;
20
21pub const DEFAULT: DefaultThreadPinner = DefaultThreadPinner {};
22
23#[cfg_attr(feature = "mockall", mockall::automock)]
24pub trait ThreadPinner: Send + Sync {
25    fn pin_current_thread_to(&self, core_id: LogicalCoreId) -> bool;
26
27    fn pin_current_thread_to_cpuset(&self, core_ids: &[LogicalCoreId]) -> bool;
28}
29
30pub struct DefaultThreadPinner;
31
32impl ThreadPinner for DefaultThreadPinner {
33    #[inline]
34    fn pin_current_thread_to(&self, core_id: LogicalCoreId) -> bool {
35        let core_id = CoreId { id: core_id.into() };
36        ccp_core_affinity::set_for_current(core_id)
37    }
38
39    #[inline]
40    fn pin_current_thread_to_cpuset(&self, core_ids: &[LogicalCoreId]) -> bool {
41        let core_ids = core_ids
42            .iter()
43            .map(|core_id| {
44                let id = (*core_id).into();
45                CoreId { id }
46            })
47            .collect::<Vec<_>>();
48
49        ccp_core_affinity::set_mask_for_current(&core_ids)
50    }
51}