1 /*
2  * Copyright (c) 2023-2023 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 "thread_utils.h"
17 #include <sys/resource.h>
18 #include "dp_log.h"
19 
20 namespace OHOS {
21 namespace CameraStandard {
22 namespace DeferredProcessing {
23 extern "C" pid_t __attribute__((weak)) pthread_gettid_np(pthread_t threadId);
24 
SetThreadName(pthread_t tid,const std::string & name)25 void SetThreadName(pthread_t tid, const std::string& name)
26 {
27     constexpr int threadNameMaxSize = 15;
28     auto threadName = name.size() > threadNameMaxSize ? name.substr(0, threadNameMaxSize).c_str() : name;
29     if (name.size() > threadNameMaxSize) {
30         DP_DEBUG_LOG("task name %s exceed max size: %{public}d", name.c_str(), threadNameMaxSize);
31     }
32     int ret = pthread_setname_np(tid, threadName.c_str());
33     DP_DEBUG_LOG("threadId: %ld, threadName: %s, pthread_setname_np ret = %{public}d.",
34         static_cast<long>(pthread_gettid_np(tid)), threadName.c_str(), ret);
35 }
36 
SetThreadPriority(pthread_t handle,int priority)37 void SetThreadPriority(pthread_t handle, int priority)
38 {
39     pid_t tid = pthread_gettid_np(handle);
40     int currPri = getpriority(PRIO_PROCESS, tid);
41     if (currPri == priority) {
42         return;
43     }
44     int ret = setpriority(PRIO_PROCESS, tid, priority);
45     if (ret == 0) {
46         DP_DEBUG_LOG("succeed for tid (%ld) with priority (%{public}d).", static_cast<long>(tid), priority);
47     } else {
48         DP_DEBUG_LOG("failed for tid (%ld) with priority (%{public}d), ret = %{public}d.",
49             static_cast<long>(tid), priority, ret);
50     }
51 }
52 
GetThreadPriority(pthread_t handle)53 int GetThreadPriority(pthread_t handle)
54 {
55     pid_t tid = pthread_gettid_np(handle);
56     return getpriority(PRIO_PROCESS, tid);
57 }
58 } //namespace DeferredProcessing
59 } // namespace CameraStandard
60 } // namespace OHOS
61