xref: /aosp_15_r20/external/cronet/base/threading/platform_thread_internal_posix.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2015 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/threading/platform_thread_internal_posix.h"
6 
7 #include <errno.h>
8 #include <sys/resource.h>
9 
10 #include <ostream>
11 
12 #include "base/containers/adapters.h"
13 #include "base/logging.h"
14 #include "base/notimplemented.h"
15 #include "base/notreached.h"
16 
17 namespace base {
18 
19 namespace internal {
20 
ThreadTypeToNiceValue(ThreadType thread_type)21 BASE_EXPORT int ThreadTypeToNiceValue(ThreadType thread_type) {
22   for (const auto& pair : kThreadTypeToNiceValueMap) {
23     if (pair.thread_type == thread_type)
24       return pair.nice_value;
25   }
26   NOTREACHED() << "Unknown ThreadType";
27   return 0;
28 }
29 
NiceValueToThreadPriorityForTest(int nice_value)30 ThreadPriorityForTest NiceValueToThreadPriorityForTest(int nice_value) {
31   // Try to find a priority that best describes |nice_value|. If there isn't
32   // an exact match, this method returns the closest priority whose nice value
33   // is higher (lower priority) than |nice_value|.
34   for (const auto& pair : kThreadPriorityToNiceValueMapForTest) {
35     if (pair.nice_value >= nice_value)
36       return pair.priority;
37   }
38 
39   // Reaching here means |nice_value| is more than any of the defined
40   // priorities. The lowest priority is suitable in this case.
41   return ThreadPriorityForTest::kBackground;
42 }
43 
GetCurrentThreadNiceValue()44 int GetCurrentThreadNiceValue() {
45 #if BUILDFLAG(IS_NACL)
46   NOTIMPLEMENTED();
47   return 0;
48 #else
49 
50   // Need to clear errno before calling getpriority():
51   // http://man7.org/linux/man-pages/man2/getpriority.2.html
52   errno = 0;
53   int nice_value = getpriority(PRIO_PROCESS, 0);
54   if (errno != 0) {
55     DVPLOG(1) << "Failed to get nice value of thread ("
56               << PlatformThread::CurrentId() << ")";
57     return 0;
58   }
59 
60   return nice_value;
61 #endif
62 }
63 
64 }  // namespace internal
65 
66 }  // namespace base
67