|
| 1 | +// Copyright 2024 eSOL Co.,Ltd. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +#include <sys/types.h> |
| 16 | +#include <sched.h> |
| 17 | + |
| 18 | +#include <stdexcept> |
| 19 | +#include <iostream> |
| 20 | + |
| 21 | +#include "rcpputils/thread/detail/posix/thread.hpp" |
| 22 | +#include "rcpputils/thread/detail/posix/utilities.hpp" |
| 23 | +#include "./thread_impl.hpp" |
| 24 | + |
| 25 | +namespace rcpputils |
| 26 | +{ |
| 27 | + |
| 28 | +namespace this_thread |
| 29 | +{ |
| 30 | + |
| 31 | +using thread::detail::UniqueNativeCpuSet; |
| 32 | +using thread::detail::make_unique_native_cpu_set; |
| 33 | +using thread::detail::throw_if_error; |
| 34 | +using thread::detail::to_native_sched_policy; |
| 35 | + |
| 36 | +void apply_sched_options(SchedOptions const & options) |
| 37 | +{ |
| 38 | + pid_t tid = gettid(); |
| 39 | + if (options.policy) { |
| 40 | + int native_sched_policy = to_native_sched_policy(*options.policy); |
| 41 | + sched_param param; |
| 42 | + int r; |
| 43 | + if (options.priority) { |
| 44 | + param.sched_priority = *options.priority; |
| 45 | + } else { |
| 46 | + r = sched_getparam(tid, ¶m); |
| 47 | + throw_if_error(r, "error in sched_getparam"); |
| 48 | + } |
| 49 | + r = sched_setscheduler(tid, native_sched_policy, ¶m); |
| 50 | + throw_if_error(r, "error in sched_setscheduler"); |
| 51 | + } else if (options.priority) { |
| 52 | + sched_param param; |
| 53 | + param.sched_priority = *options.priority; |
| 54 | + int r = sched_setparam(tid, ¶m); |
| 55 | + throw_if_error(r, "error in sched_setparam"); |
| 56 | + } |
| 57 | + if (options.core_affinity) { |
| 58 | + UniqueNativeCpuSet native_cpu_set = make_unique_native_cpu_set(*options.core_affinity); |
| 59 | + std::size_t sz = CPU_ALLOC_SIZE(options.core_affinity->count()); |
| 60 | + int r = sched_setaffinity(tid, sz, native_cpu_set.get()); |
| 61 | + throw_if_error(r, "error in sched_setaffinity"); |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +} // namespace this_thread |
| 66 | +} // namespace rcpputils |
0 commit comments