thread_pool.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. // Copyright 2019 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_H_
  5. #define BASE_TASK_THREAD_POOL_H_
  6. #include <memory>
  7. #include <utility>
  8. #include "base/base_export.h"
  9. #include "base/bind.h"
  10. #include "base/callback.h"
  11. #include "base/callback_helpers.h"
  12. #include "base/location.h"
  13. #include "base/memory/scoped_refptr.h"
  14. #include "base/task/post_task_and_reply_with_result_internal.h"
  15. #include "base/task/sequenced_task_runner.h"
  16. #include "base/task/single_thread_task_runner.h"
  17. #include "base/task/single_thread_task_runner_thread_mode.h"
  18. #include "base/task/task_runner.h"
  19. #include "base/task/task_traits.h"
  20. #include "base/task/updateable_sequenced_task_runner.h"
  21. #include "base/time/time.h"
  22. #include "build/build_config.h"
  23. namespace base {
  24. // This is the interface to post tasks to base's thread pool.
  25. //
  26. // To post a simple one-off task with default traits:
  27. // base::ThreadPool::PostTask(FROM_HERE, base::BindOnce(...));
  28. //
  29. // To post a high priority one-off task to respond to a user interaction:
  30. // base::ThreadPool::PostTask(
  31. // FROM_HERE,
  32. // {base::TaskPriority::USER_BLOCKING},
  33. // base::BindOnce(...));
  34. //
  35. // To post tasks that must run in sequence with default traits:
  36. // scoped_refptr<SequencedTaskRunner> task_runner =
  37. // base::ThreadPool::CreateSequencedTaskRunner();
  38. // task_runner->PostTask(FROM_HERE, base::BindOnce(...));
  39. // task_runner->PostTask(FROM_HERE, base::BindOnce(...));
  40. //
  41. // To post tasks that may block, must run in sequence and can be skipped on
  42. // shutdown:
  43. // scoped_refptr<SequencedTaskRunner> task_runner =
  44. // base::ThreadPool::CreateSequencedTaskRunner(
  45. // {MayBlock(), TaskShutdownBehavior::SKIP_ON_SHUTDOWN});
  46. // task_runner->PostTask(FROM_HERE, base::BindOnce(...));
  47. // task_runner->PostTask(FROM_HERE, base::BindOnce(...));
  48. //
  49. // The default traits apply to tasks that:
  50. // (1) don't block (ref. MayBlock() and WithBaseSyncPrimitives()),
  51. // (2) prefer inheriting the current priority to specifying their own, and
  52. // (3) can either block shutdown or be skipped on shutdown
  53. // (implementation is free to choose a fitting default).
  54. // Explicit traits must be specified for tasks for which these loose
  55. // requirements are not sufficient.
  56. //
  57. // Prerequisite: A ThreadPoolInstance must have been registered for the current
  58. // process via ThreadPoolInstance::Set() before the API below can be invoked.
  59. // This is typically done during the initialization phase in each process. If
  60. // your code is not running in that phase, you most likely don't have to worry
  61. // about this. You will encounter DCHECKs or nullptr dereferences if this is
  62. // violated. For tests, use base::test::TaskEnvironment.
  63. class BASE_EXPORT ThreadPool {
  64. public:
  65. // base::ThreadPool is a static API. See base::ThreadPoolInstance for the
  66. // actual instance.
  67. ThreadPool() = delete;
  68. // Equivalent to calling PostTask with default TaskTraits.
  69. static bool PostTask(const Location& from_here, OnceClosure task);
  70. inline static bool PostTask(OnceClosure task,
  71. const Location& from_here = Location::Current()) {
  72. return PostTask(from_here, std::move(task));
  73. }
  74. // Equivalent to calling PostDelayedTask with default TaskTraits.
  75. //
  76. // Use PostDelayedTask to specify a BEST_EFFORT priority if the task doesn't
  77. // have to run as soon as |delay| expires.
  78. static bool PostDelayedTask(const Location& from_here,
  79. OnceClosure task,
  80. TimeDelta delay);
  81. // Equivalent to calling PostTaskAndReply with default TaskTraits.
  82. static bool PostTaskAndReply(const Location& from_here,
  83. OnceClosure task,
  84. OnceClosure reply);
  85. // Equivalent to calling PostTaskAndReplyWithResult with default TaskTraits.
  86. //
  87. // Though RepeatingCallback is convertible to OnceCallback, we need a
  88. // CallbackType template since we can not use template deduction and object
  89. // conversion at once on the overload resolution.
  90. // TODO(crbug.com/714018): Update all callers of the RepeatingCallback version
  91. // to use OnceCallback and remove the CallbackType template.
  92. template <template <typename> class CallbackType,
  93. typename TaskReturnType,
  94. typename ReplyArgType,
  95. typename = EnableIfIsBaseCallback<CallbackType>>
  96. static bool PostTaskAndReplyWithResult(
  97. const Location& from_here,
  98. CallbackType<TaskReturnType()> task,
  99. CallbackType<void(ReplyArgType)> reply) {
  100. return ThreadPool::PostTaskAndReplyWithResult(
  101. from_here, {}, std::move(task), std::move(reply));
  102. }
  103. // Posts |task| with specific |traits|. Returns false if the task definitely
  104. // won't run because of current shutdown state.
  105. static bool PostTask(const Location& from_here,
  106. const TaskTraits& traits,
  107. OnceClosure task);
  108. // Posts |task| with specific |traits|. |task| will not run before |delay|
  109. // expires. Returns false if the task definitely won't run because of current
  110. // shutdown state.
  111. //
  112. // Specify a BEST_EFFORT priority via |traits| if the task doesn't have to run
  113. // as soon as |delay| expires.
  114. static bool PostDelayedTask(const Location& from_here,
  115. const TaskTraits& traits,
  116. OnceClosure task,
  117. TimeDelta delay);
  118. // Posts |task| with specific |traits| and posts |reply| on the caller's
  119. // execution context (i.e. same sequence or thread and same TaskTraits if
  120. // applicable) when |task| completes. Returns false if the task definitely
  121. // won't run because of current shutdown state. Can only be called when
  122. // SequencedTaskRunnerHandle::IsSet().
  123. static bool PostTaskAndReply(const Location& from_here,
  124. const TaskTraits& traits,
  125. OnceClosure task,
  126. OnceClosure reply);
  127. // Posts |task| with specific |traits| and posts |reply| with the return value
  128. // of |task| as argument on the caller's execution context (i.e. same sequence
  129. // or thread and same TaskTraits if applicable) when |task| completes. Returns
  130. // false if the task definitely won't run because of current shutdown state.
  131. // Can only be called when SequencedTaskRunnerHandle::IsSet().
  132. //
  133. // Though RepeatingCallback is convertible to OnceCallback, we need a
  134. // CallbackType template since we can not use template deduction and object
  135. // conversion at once on the overload resolution.
  136. // TODO(crbug.com/714018): Update all callers of the RepeatingCallback version
  137. // to use OnceCallback and remove the CallbackType template.
  138. template <template <typename> class CallbackType,
  139. typename TaskReturnType,
  140. typename ReplyArgType,
  141. typename = EnableIfIsBaseCallback<CallbackType>>
  142. static bool PostTaskAndReplyWithResult(
  143. const Location& from_here,
  144. const TaskTraits& traits,
  145. CallbackType<TaskReturnType()> task,
  146. CallbackType<void(ReplyArgType)> reply) {
  147. auto* result = new std::unique_ptr<TaskReturnType>();
  148. return PostTaskAndReply(
  149. from_here, traits,
  150. BindOnce(&internal::ReturnAsParamAdapter<TaskReturnType>,
  151. std::move(task), result),
  152. BindOnce(&internal::ReplyAdapter<TaskReturnType, ReplyArgType>,
  153. std::move(reply), Owned(result)));
  154. }
  155. // Returns a TaskRunner whose PostTask invocations result in scheduling tasks
  156. // using |traits|. Tasks may run in any order and in parallel.
  157. static scoped_refptr<TaskRunner> CreateTaskRunner(const TaskTraits& traits);
  158. // Returns a SequencedTaskRunner whose PostTask invocations result in
  159. // scheduling tasks using |traits|. Tasks run one at a time in posting order.
  160. static scoped_refptr<SequencedTaskRunner> CreateSequencedTaskRunner(
  161. const TaskTraits& traits);
  162. // Returns a task runner whose PostTask invocations result in scheduling tasks
  163. // using |traits|. The priority in |traits| can be updated at any time via
  164. // UpdateableSequencedTaskRunner::UpdatePriority(). An update affects all
  165. // tasks posted to the task runner that aren't running yet. Tasks run one at a
  166. // time in posting order.
  167. //
  168. // |traits| requirements:
  169. // - base::ThreadPolicy must be specified if the priority of the task runner
  170. // will ever be increased from BEST_EFFORT.
  171. static scoped_refptr<UpdateableSequencedTaskRunner>
  172. CreateUpdateableSequencedTaskRunner(const TaskTraits& traits);
  173. // Returns a SingleThreadTaskRunner whose PostTask invocations result in
  174. // scheduling tasks using |traits| on a thread determined by |thread_mode|.
  175. // See base/task/single_thread_task_runner_thread_mode.h for |thread_mode|
  176. // details. If |traits| identifies an existing thread,
  177. // SingleThreadTaskRunnerThreadMode::SHARED must be used. Tasks run on a
  178. // single thread in posting order.
  179. //
  180. // If all you need is to make sure that tasks don't run concurrently (e.g.
  181. // because they access a data structure which is not thread-safe), use
  182. // CreateSequencedTaskRunner(). Only use this if you rely on a thread-affine
  183. // API (it might be safer to assume thread-affinity when dealing with
  184. // under-documented third-party APIs, e.g. other OS') or share data across
  185. // tasks using thread-local storage.
  186. static scoped_refptr<SingleThreadTaskRunner> CreateSingleThreadTaskRunner(
  187. const TaskTraits& traits,
  188. SingleThreadTaskRunnerThreadMode thread_mode =
  189. SingleThreadTaskRunnerThreadMode::SHARED);
  190. #if BUILDFLAG(IS_WIN)
  191. // Returns a SingleThreadTaskRunner whose PostTask invocations result in
  192. // scheduling tasks using |traits| in a COM Single-Threaded Apartment on a
  193. // thread determined by |thread_mode|. See
  194. // base/task/single_thread_task_runner_thread_mode.h for |thread_mode|
  195. // details. If |traits| identifies an existing thread,
  196. // SingleThreadTaskRunnerThreadMode::SHARED must be used. Tasks run in the
  197. // same Single-Threaded Apartment in posting order for the returned
  198. // SingleThreadTaskRunner. There is not necessarily a one-to-one
  199. // correspondence between SingleThreadTaskRunners and Single-Threaded
  200. // Apartments. The implementation is free to share apartments or create new
  201. // apartments as necessary. In either case, care should be taken to make sure
  202. // COM pointers are not smuggled across apartments.
  203. static scoped_refptr<SingleThreadTaskRunner> CreateCOMSTATaskRunner(
  204. const TaskTraits& traits,
  205. SingleThreadTaskRunnerThreadMode thread_mode =
  206. SingleThreadTaskRunnerThreadMode::SHARED);
  207. #endif // BUILDFLAG(IS_WIN)
  208. };
  209. } // namespace base
  210. #endif // BASE_TASK_THREAD_POOL_H_