• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2018 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 #ifndef BASE_TASK_SCHEDULER_SERVICE_THREAD_H_
6 #define BASE_TASK_SCHEDULER_SERVICE_THREAD_H_
7 
8 #include "base/base_export.h"
9 #include "base/macros.h"
10 #include "base/threading/thread.h"
11 #include "base/time/time.h"
12 #include "base/timer/timer.h"
13 
14 namespace base {
15 namespace internal {
16 
17 class TaskTracker;
18 
19 // The TaskScheduler's ServiceThread is a mostly idle thread that is responsible
20 // for handling async events (e.g. delayed tasks and async I/O). Its role is to
21 // merely forward such events to their destination (hence staying mostly idle
22 // and highly responsive).
23 // It aliases Thread::Run() to enforce that ServiceThread::Run() be on the stack
24 // and make it easier to identify the service thread in stack traces.
25 class BASE_EXPORT ServiceThread : public Thread {
26  public:
27   // Constructs a ServiceThread which will report latency metrics through
28   // |task_tracker| if non-null. In that case, this ServiceThread will assume a
29   // registered TaskScheduler instance and that |task_tracker| will outlive this
30   // ServiceThread.
31   explicit ServiceThread(const TaskTracker* task_tracker);
32 
33   // Overrides the default interval at which |heartbeat_latency_timer_| fires.
34   // Call this with a |heartbeat| of zero to undo the override.
35   // Must not be called while the ServiceThread is running.
36   static void SetHeartbeatIntervalForTesting(TimeDelta heartbeat);
37 
38  private:
39   // Thread:
40   void Init() override;
41   void Run(RunLoop* run_loop) override;
42 
43   // Kicks off a single async task which will record a histogram on the latency
44   // of a randomly chosen set of TaskTraits.
45   void PerformHeartbeatLatencyReport() const;
46 
47   const TaskTracker* const task_tracker_;
48 
49   // Fires a recurring heartbeat task to record latency histograms which are
50   // independent from any execution sequence. This is done on the service thread
51   // to avoid all external dependencies (even main thread).
52   base::RepeatingTimer heartbeat_latency_timer_;
53 
54   DISALLOW_COPY_AND_ASSIGN(ServiceThread);
55 };
56 
57 }  // namespace internal
58 }  // namespace base
59 
60 #endif  // BASE_TASK_SCHEDULER_SERVICE_THREAD_H_
61