service_thread.h 2.2 KB

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