1 /*
2  * Copyright (C) 2024 Huawei Device Co., Ltd.
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 
16 #include "cpu_utils.h"
17 
18 #include <cerrno>
19 #include <pthread.h>
20 #include <sched.h>
21 #include <unistd.h>
22 
23 #include "media_log.h"
24 
25 namespace OHOS {
26 namespace Media {
SlowDown()27 void CpuUtils::SlowDown()
28 {
29     cpu_set_t cpuSet;
30     CPU_ZERO(&cpuSet);
31     for (int cpu = CpuAffinityType::CPU_IDX_0; cpu <= CpuAffinityType::CPU_IDX_6; cpu++) {
32         CPU_SET(cpu, &cpuSet);
33     }
34     if (sched_setaffinity(0, sizeof(cpuSet), &cpuSet) < 0) {
35         MEDIA_ERR_LOG("set thread affinity failed, errno %{public}d", errno);
36     }
37 }
38 
ResetCpu()39 void CpuUtils::ResetCpu()
40 {
41     cpu_set_t cpuSet;
42     CPU_ZERO(&cpuSet);
43 
44     if (sched_setaffinity(0, sizeof(cpuSet), &cpuSet) < 0) {
45         MEDIA_ERR_LOG("set thread affinity failed, errno %{public}d", errno);
46         return;
47     }
48 }
49 
SetSelfThreadAffinity(CpuAffinityType cpuAffinityType)50 void CpuUtils::SetSelfThreadAffinity(CpuAffinityType cpuAffinityType)
51 {
52     if (cpuAffinityType < CpuAffinityType::CPU_IDX_0) {
53         return;
54     }
55 
56     cpu_set_t cpuSet;
57     CPU_ZERO(&cpuSet);
58     for (int cpu = CpuAffinityType::CPU_IDX_0; cpu <= cpuAffinityType; cpu++) {
59         CPU_SET(cpu, &cpuSet);
60     }
61 
62     if (pthread_setaffinity_np(pthread_self(), sizeof(cpuSet), &cpuSet) != 0) {
63         MEDIA_WARN_LOG("Set affinity failed, errno %{public}d, cpuAffinityType:%{public}d", errno, cpuAffinityType);
64     }
65 }
66 
ResetSelfThreadAffinity()67 void CpuUtils::ResetSelfThreadAffinity()
68 {
69     cpu_set_t cpuSet;
70     CPU_ZERO(&cpuSet);
71     if (pthread_setaffinity_np(pthread_self(), sizeof(cpuSet), &cpuSet) != 0) {
72         MEDIA_WARN_LOG("Reset affinity failed, errno %{public}d", errno);
73     }
74 }
75 } // namespace Media
76 } // namespace OHOS
77