1 // Copyright 2017 The Chromium Authors. All rights reserved.
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/task_scheduler/environment_config.h"
6 
7 #include "base/synchronization/lock.h"
8 #include "base/threading/platform_thread.h"
9 #include "build/build_config.h"
10 
11 namespace base {
12 namespace internal {
13 
GetEnvironmentIndexForTraits(const TaskTraits & traits)14 size_t GetEnvironmentIndexForTraits(const TaskTraits& traits) {
15   const bool is_background =
16       traits.priority() == base::TaskPriority::BACKGROUND;
17   if (traits.may_block() || traits.with_base_sync_primitives())
18     return is_background ? BACKGROUND_BLOCKING : FOREGROUND_BLOCKING;
19   return is_background ? BACKGROUND : FOREGROUND;
20 }
21 
CanUseBackgroundPriorityForSchedulerWorker()22 bool CanUseBackgroundPriorityForSchedulerWorker() {
23   // When Lock doesn't handle multiple thread priorities, run all
24   // SchedulerWorker with a normal priority to avoid priority inversion when a
25   // thread running with a normal priority tries to acquire a lock held by a
26   // thread running with a background priority.
27   if (!Lock::HandlesMultipleThreadPriorities())
28     return false;
29 
30 #if !defined(OS_ANDROID)
31   // When thread priority can't be increased, run all threads with a normal
32   // priority to avoid priority inversions on shutdown (TaskScheduler increases
33   // background threads priority to normal on shutdown while resolving remaining
34   // shutdown blocking tasks).
35   //
36   // This is ignored on Android, because it doesn't have a clean shutdown phase.
37   if (!PlatformThread::CanIncreaseCurrentThreadPriority())
38     return false;
39 #endif  // defined(OS_ANDROID)
40 
41   return true;
42 }
43 
44 }  // namespace internal
45 }  // namespace base
46