thread_pool_impl.h 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. // Copyright 2016 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_THREAD_POOL_IMPL_H_
  5. #define BASE_TASK_THREAD_POOL_THREAD_POOL_IMPL_H_
  6. #include <memory>
  7. #include <vector>
  8. #include "base/base_export.h"
  9. #include "base/callback.h"
  10. #include "base/check_op.h"
  11. #include "base/macros.h"
  12. #include "base/memory/ptr_util.h"
  13. #include "base/memory/ref_counted.h"
  14. #include "base/optional.h"
  15. #include "base/sequence_checker.h"
  16. #include "base/strings/string_piece.h"
  17. #include "base/synchronization/atomic_flag.h"
  18. #include "base/task/single_thread_task_runner_thread_mode.h"
  19. #include "base/task/task_executor.h"
  20. #include "base/task/task_traits.h"
  21. #include "base/task/thread_pool/delayed_task_manager.h"
  22. #include "base/task/thread_pool/environment_config.h"
  23. #include "base/task/thread_pool/pooled_single_thread_task_runner_manager.h"
  24. #include "base/task/thread_pool/pooled_task_runner_delegate.h"
  25. #include "base/task/thread_pool/task_source.h"
  26. #include "base/task/thread_pool/task_tracker.h"
  27. #include "base/task/thread_pool/thread_group.h"
  28. #include "base/task/thread_pool/thread_group_impl.h"
  29. #include "base/task/thread_pool/thread_pool_instance.h"
  30. #include "base/updateable_sequenced_task_runner.h"
  31. #include "build/build_config.h"
  32. #if defined(OS_POSIX) && !defined(OS_NACL_SFI)
  33. #include "base/task/thread_pool/task_tracker_posix.h"
  34. #endif
  35. #if defined(OS_WIN)
  36. #include "base/win/com_init_check_hook.h"
  37. #endif
  38. namespace base {
  39. class Thread;
  40. namespace internal {
  41. // Default ThreadPoolInstance implementation. This class is thread-safe.
  42. class BASE_EXPORT ThreadPoolImpl : public ThreadPoolInstance,
  43. public TaskExecutor,
  44. public ThreadGroup::Delegate,
  45. public PooledTaskRunnerDelegate {
  46. public:
  47. using TaskTrackerImpl =
  48. #if defined(OS_POSIX) && !defined(OS_NACL_SFI)
  49. TaskTrackerPosix;
  50. #else
  51. TaskTracker;
  52. #endif
  53. // Creates a ThreadPoolImpl with a production TaskTracker. |histogram_label|
  54. // is used to label histograms. No histograms are recorded if it is empty.
  55. explicit ThreadPoolImpl(StringPiece histogram_label);
  56. // For testing only. Creates a ThreadPoolImpl with a custom TaskTracker.
  57. ThreadPoolImpl(StringPiece histogram_label,
  58. std::unique_ptr<TaskTrackerImpl> task_tracker);
  59. ~ThreadPoolImpl() override;
  60. // ThreadPoolInstance:
  61. void Start(const ThreadPoolInstance::InitParams& init_params,
  62. WorkerThreadObserver* worker_thread_observer) override;
  63. int GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated(
  64. const TaskTraits& traits) const override;
  65. void Shutdown() override;
  66. void FlushForTesting() override;
  67. void FlushAsyncForTesting(OnceClosure flush_callback) override;
  68. void JoinForTesting() override;
  69. void BeginFence() override;
  70. void EndFence() override;
  71. void BeginBestEffortFence() override;
  72. void EndBestEffortFence() override;
  73. // TaskExecutor:
  74. bool PostDelayedTask(const Location& from_here,
  75. const TaskTraits& traits,
  76. OnceClosure task,
  77. TimeDelta delay) override;
  78. scoped_refptr<TaskRunner> CreateTaskRunner(const TaskTraits& traits) override;
  79. scoped_refptr<SequencedTaskRunner> CreateSequencedTaskRunner(
  80. const TaskTraits& traits) override;
  81. scoped_refptr<SingleThreadTaskRunner> CreateSingleThreadTaskRunner(
  82. const TaskTraits& traits,
  83. SingleThreadTaskRunnerThreadMode thread_mode) override;
  84. #if defined(OS_WIN)
  85. scoped_refptr<SingleThreadTaskRunner> CreateCOMSTATaskRunner(
  86. const TaskTraits& traits,
  87. SingleThreadTaskRunnerThreadMode thread_mode) override;
  88. #endif // defined(OS_WIN)
  89. scoped_refptr<UpdateableSequencedTaskRunner>
  90. CreateUpdateableSequencedTaskRunner(const TaskTraits& traits);
  91. // PooledTaskRunnerDelegate:
  92. bool EnqueueJobTaskSource(scoped_refptr<JobTaskSource> task_source) override;
  93. void RemoveJobTaskSource(scoped_refptr<JobTaskSource> task_source) override;
  94. void UpdatePriority(scoped_refptr<TaskSource> task_source,
  95. TaskPriority priority) override;
  96. // Returns the TimeTicks of the next task scheduled on ThreadPool (Now() if
  97. // immediate, nullopt if none). This is thread-safe, i.e., it's safe if tasks
  98. // are being posted in parallel with this call but such a situation obviously
  99. // results in a race as to whether this call will see the new tasks in time.
  100. Optional<TimeTicks> NextScheduledRunTimeForTesting() const;
  101. // Forces ripe delayed tasks to be posted (e.g. when time is mocked and
  102. // advances faster than the real-time delay on ServiceThread).
  103. void ProcessRipeDelayedTasksForTesting();
  104. // Requests that all threads started by future ThreadPoolImpls in this process
  105. // have a synchronous start (if |enabled|; cancels this behavior otherwise).
  106. // Must be called while no ThreadPoolImpls are alive in this process. This is
  107. // exposed here on this internal API rather than as a ThreadPoolInstance
  108. // configuration param because only one internal test truly needs this.
  109. static void SetSynchronousThreadStartForTesting(bool enabled);
  110. private:
  111. // Invoked after |num_fences_| or |num_best_effort_fences_| is updated. Sets
  112. // the CanRunPolicy in TaskTracker and wakes up workers as appropriate.
  113. void UpdateCanRunPolicy();
  114. // Verifies that |traits| do not have properties that are banned in ThreadPool
  115. // and returns |traits|, with priority set to TaskPriority::USER_BLOCKING if
  116. // |all_tasks_user_blocking_| is set.
  117. TaskTraits VerifyAndAjustIncomingTraits(TaskTraits traits) const;
  118. const ThreadGroup* GetThreadGroupForTraits(const TaskTraits& traits) const;
  119. // ThreadGroup::Delegate:
  120. ThreadGroup* GetThreadGroupForTraits(const TaskTraits& traits) override;
  121. // Posts |task| to be executed by the appropriate thread group as part of
  122. // |sequence|. This must only be called after |task| has gone through
  123. // TaskTracker::WillPostTask() and after |task|'s delayed run time.
  124. bool PostTaskWithSequenceNow(Task task, scoped_refptr<Sequence> sequence);
  125. // PooledTaskRunnerDelegate:
  126. bool PostTaskWithSequence(Task task,
  127. scoped_refptr<Sequence> sequence) override;
  128. bool ShouldYield(const TaskSource* task_source) const override;
  129. const std::unique_ptr<TaskTrackerImpl> task_tracker_;
  130. std::unique_ptr<Thread> service_thread_;
  131. DelayedTaskManager delayed_task_manager_;
  132. PooledSingleThreadTaskRunnerManager single_thread_task_runner_manager_;
  133. // Indicates that all tasks are handled as if they had been posted with
  134. // TaskPriority::USER_BLOCKING. Since this is set in Start(), it doesn't apply
  135. // to tasks posted before Start() or to tasks posted to TaskRunners created
  136. // before Start().
  137. //
  138. // TODO(fdoray): Remove after experiment. https://crbug.com/757022
  139. AtomicFlag all_tasks_user_blocking_;
  140. std::unique_ptr<ThreadGroup> foreground_thread_group_;
  141. std::unique_ptr<ThreadGroupImpl> background_thread_group_;
  142. // Whether this TaskScheduler was started. Access controlled by
  143. // |sequence_checker_|.
  144. bool started_ = false;
  145. // Whether the --disable-best-effort-tasks switch is preventing execution of
  146. // BEST_EFFORT tasks until shutdown.
  147. const bool has_disable_best_effort_switch_;
  148. // Number of fences preventing execution of tasks of any/BEST_EFFORT priority.
  149. // Access controlled by |sequence_checker_|.
  150. int num_fences_ = 0;
  151. int num_best_effort_fences_ = 0;
  152. #if DCHECK_IS_ON()
  153. // Set once JoinForTesting() has returned.
  154. AtomicFlag join_for_testing_returned_;
  155. #endif
  156. #if defined(OS_WIN) && defined(COM_INIT_CHECK_HOOK_ENABLED)
  157. // Provides COM initialization verification for supported builds.
  158. base::win::ComInitCheckHook com_init_check_hook_;
  159. #endif
  160. // Asserts that operations occur in sequence with Start().
  161. SEQUENCE_CHECKER(sequence_checker_);
  162. TrackedRefFactory<ThreadGroup::Delegate> tracked_ref_factory_;
  163. DISALLOW_COPY_AND_ASSIGN(ThreadPoolImpl);
  164. };
  165. } // namespace internal
  166. } // namespace base
  167. #endif // BASE_TASK_THREAD_POOL_THREAD_POOL_IMPL_H_