| 6 | #define BASE_TASK_TASK_TRAITS_H_ |
| 7 |
| 8 | #include <stdint.h> |
| 9 |
| 10 | #include <iosfwd> |
| 11 | #include <tuple> |
| 12 | #include <type_traits> |
| 13 | #include <utility> |
| 14 |
| 15 | #include "base/base_export.h" |
| 16 | #include "base/logging.h" |
| 17 | #include "base/task/task_traits_extension.h" |
| 18 | #include "base/traits_bag.h" |
| 19 | #include "build/build_config.h" |
| 20 |
| 21 | // TODO(gab): This is backwards, thread_pool.h should include task_traits.h |
| 22 | // but it this is necessary to have it in this direction during the migration |
| 23 | // from old code that used base::ThreadPool as a trait. |
| 24 | #include "base/task/thread_pool.h" |
| 25 |
| 26 | namespace base { |
| 27 |
| 28 | class PostTaskAndroid; |
| 29 |
| 30 | // Valid priorities supported by the task scheduling infrastructure. |
| 31 | // |
| 32 | // Note: internal algorithms depend on priorities being expressed as a |
| 33 | // continuous zero-based list from lowest to highest priority. Users of this API |
| 34 | // shouldn't otherwise care about nor use the underlying values. |
| 35 | // |
| 36 | // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.base.task |
| 37 | enum class TaskPriority : uint8_t { |
| 38 | // This will always be equal to the lowest priority available. |
| 39 | LOWEST = 0, |
| 40 | // This task will only start running when machine resources are available. The |
| 41 | // application may preempt the task if it expects that resources will soon be |
| 42 | // needed by work of higher priority. Dependending on the ThreadPolicy, the |
| 43 | // task may run on a thread that is likely to be descheduled when higher |
| 44 | // priority work arrives (in this process or another). |
| 45 | // |
| 46 | // Examples: |
| 47 | // - Reporting metrics. |
| 48 | // - Persisting data to disk. |
| 49 | // - Loading data that is required for a potential future user interaction |
| 50 | // (Note: Use CreateUpdateableSequencedTaskRunner() to increase the priority |
| 51 | // when that user interactions happens). |
| 52 | BEST_EFFORT = LOWEST, |
| 53 |
| 54 | // The result of this task is visible to the user (in the UI or as a |
| 55 | // side-effect on the system) but it is not an immediate response to a user |
| 56 | // interaction. |
| 57 | // |
| 58 | // Examples: |
| 59 | // - Updating the UI to reflect progress on a long task. |
| 60 | // - Downloading a file requested by the user. |
| 61 | // - Loading an image that is displayed in the UI but is non-critical. |
| 62 | USER_VISIBLE, |
| 63 |
| 64 | // This task affects UI immediately after a user interaction. |
| 65 | // |
| 66 | // Example: |
| 67 | // - Loading and rendering a web page after the user clicks a link. |
| 68 | // - Sorting suggestions after the user types a character in the omnibox. |
| 69 | // |
| 70 | // This is the default TaskPriority in order for tasks to run in order by |
| 71 | // default and avoid unintended consequences. The only way to get a task to |
| 72 | // run at a higher priority than USER_BLOCKING is to coordinate with a |
| 73 | // higher-level scheduler (contact scheduler-dev@chromium.org for such use |
| 74 | // cases). |
| 75 | USER_BLOCKING, |
| 76 |
| 77 | // This will always be equal to the highest priority available. |
| 78 | HIGHEST = USER_BLOCKING |
| 79 | }; |
| 80 |
| 81 | // Valid shutdown behaviors supported by the thread pool. |
| 82 | enum class TaskShutdownBehavior : uint8_t { |
| 83 | // Tasks posted with this mode which have not started executing before |
| 84 | // shutdown is initiated will never run. Tasks with this mode running at |
| 85 | // shutdown will be ignored (the worker will not be joined). |
| 86 | // |
| 87 | // This option provides a nice way to post stuff you don't want blocking |
| 88 | // shutdown. For example, you might be doing a slow DNS lookup and if it's |
| 89 | // blocked on the OS, you may not want to stop shutdown, since the result |
| 90 | // doesn't really matter at that point. |
| 91 | // |
| 92 | // However, you need to be very careful what you do in your callback when you |
| 93 | // use this option. Since the thread will continue to run until the OS |
| 94 | // terminates the process, the app can be in the process of tearing down when |
| 95 | // you're running. This means any singletons or global objects you use may |
| 96 | // suddenly become invalid out from under you. For this reason, it's best to |
| 97 | // use this only for slow but simple operations like the DNS example. |
| 98 | CONTINUE_ON_SHUTDOWN, |
| 99 |
| 100 | // Tasks posted with this mode that have not started executing at |
| 101 | // shutdown will never run. However, any task that has already begun |
| 102 | // executing when shutdown is invoked will be allowed to continue and |
| 103 | // will block shutdown until completion. |
| 104 | // |
| 105 | // Note: Because ThreadPoolInstance::Shutdown() may block while these tasks |
| 106 | // are executing, care must be taken to ensure that they do not block on the |
| 107 | // thread that called ThreadPoolInstance::Shutdown(), as this may lead to |
| 108 | // deadlock. |
| 109 | SKIP_ON_SHUTDOWN, |
| 110 |
| 111 | // Tasks posted with this mode before shutdown is complete will block shutdown |
| 112 | // until they're executed. Generally, this should be used only to save |
| 113 | // critical user data. |
| 114 | // |
| 115 | // Note: Background threads will be promoted to normal threads at shutdown |
| 116 | // (i.e. TaskPriority::BEST_EFFORT + TaskShutdownBehavior::BLOCK_SHUTDOWN will |
| 117 | // resolve without a priority inversion). |
| 118 | BLOCK_SHUTDOWN, |
| 119 | }; |
| 120 |
| 121 | // Determines at which thread priority a task may run. |
| 122 | // |
| 123 | // ThreadPolicy and priority updates |
| 124 | // --------------------------------- |
| 125 | // |
| 126 | // If the TaskPriority of an UpdateableSequencedTaskRunner is increased while |
| 127 | // one of its tasks is running at background thread priority, the task's |
| 128 | // execution will have to complete at background thread priority (may take a |
| 129 | // long time) before the next task can be scheduled with the new TaskPriority. |
| 130 | // If it is important that priority increases take effect quickly, |
| 131 | // MUST_USE_FOREGROUND should be used to prevent the tasks from running at |
| 132 | // background thread priority. If it is important to minimize impact on the |
| 133 | // rest on the system when the TaskPriority is BEST_EFFORT, PREFER_BACKGROUND |
| 134 | // should be used. |
| 135 | // |
| 136 | // ThreadPolicy and priority inversions |
| 137 | // ------------------------------------ |
| 138 | // |
| 139 | // A priority inversion occurs when a task running at background thread |
| 140 | // priority is descheduled while holding a resource needed by a thread of |
| 141 | // higher priority. MUST_USE_FOREGROUND can be combined with BEST_EFFORT to |
| 142 | // indicate that a task has a low priority, but shouldn't run at background |
| 143 | // thread priority in order to avoid priority inversions. Please consult with |
| 144 | // //base/task/OWNERS if you suspect a priority inversion. |
| 145 | enum class ThreadPolicy : uint8_t { |
| 146 | // The task runs at background thread priority if: |
| 147 | // - The TaskPriority is BEST_EFFORT. |
| 148 | // - Background thread priority is supported by the platform (see |
| 149 | // environment_config_unittest.cc). |
| 150 | // - No extension trait (e.g. BrowserThread) is used. |
| 151 | // Otherwise, it runs at normal thread priority. |
| 152 | PREFER_BACKGROUND, |
| 153 |
| 154 | // The task runs at normal thread priority, irrespective of its TaskPriority. |
| 155 | MUST_USE_FOREGROUND |
| 156 | }; |
| 157 |
| 158 | // Tasks with this trait may block. This includes but is not limited to tasks |
| 159 | // that wait on synchronous file I/O operations: read or write a file from disk, |
| 160 | // interact with a pipe or a socket, rename or delete a file, enumerate files in |
| 161 | // a directory, etc. This trait isn't required for the mere use of locks. For |
| 162 | // tasks that block on base/ synchronization primitives, see the |
| 163 | // WithBaseSyncPrimitives trait. |
| 164 | struct MayBlock {}; |
| 165 |
| 166 | // DEPRECATED. Use base::ScopedAllowBaseSyncPrimitives(ForTesting) instead. |
| 167 | // |
| 168 | // Tasks with this trait will pass base::AssertBaseSyncPrimitivesAllowed(), i.e. |
| 169 | // will be allowed on the following methods : |
| 170 | // - base::WaitableEvent::Wait |
| 171 | // - base::ConditionVariable::Wait |
| 172 | // - base::PlatformThread::Join |
| 173 | // - base::PlatformThread::Sleep |
| 174 | // - base::Process::WaitForExit |
| 175 | // - base::Process::WaitForExitWithTimeout |
| 176 | // |
| 177 | // Tasks should generally not use these methods. |
| 178 | // |
| 179 | // Instead of waiting on a WaitableEvent or a ConditionVariable, put the work |
| 180 | // that should happen after the wait in a callback and post that callback from |
| 181 | // where the WaitableEvent or ConditionVariable would have been signaled. If |
| 182 | // something needs to be scheduled after many tasks have executed, use |
| 183 | // base::BarrierClosure. |
| 184 | // |
| 185 | // On Windows, join processes asynchronously using base::win::ObjectWatcher. |
| 186 | // |
| 187 | // MayBlock() must be specified in conjunction with this trait if and only if |
| 188 | // removing usage of methods listed above in the labeled tasks would still |
| 189 | // result in tasks that may block (per MayBlock()'s definition). |
| 190 | // |
| 191 | // In doubt, consult with //base/task/OWNERS. |
| 192 | struct WithBaseSyncPrimitives {}; |
| 193 |
| 194 | // Describes metadata for a single task or a group of tasks. |
| 195 | class BASE_EXPORT TaskTraits { |
| 196 | public: |
| 197 | // ValidTrait ensures TaskTraits' constructor only accepts appropriate types. |
| 198 | struct ValidTrait { |
| 199 | ValidTrait(TaskPriority); |
| 200 | ValidTrait(TaskShutdownBehavior); |
| 201 | ValidTrait(ThreadPolicy); |
| 202 | ValidTrait(MayBlock); |
| 203 | ValidTrait(WithBaseSyncPrimitives); |
| 204 | ValidTrait(ThreadPool); |
| 205 | }; |
| 206 |
| 207 | // Invoking this constructor without arguments produces default TaskTraits |
| 208 | // that are appropriate for tasks that |
| 209 | // (1) don't block (ref. MayBlock() and WithBaseSyncPrimitives()), |
| 210 | // (2) pertain to user-blocking activity, |
| 211 | // (explicitly or implicitly by having an ordering dependency with a |
| 212 | // component that does) |
| 213 | // (3) can either block shutdown or be skipped on shutdown |
| 214 | // (the task recipient is free to choose a fitting default). |
| 215 | // |
| 216 | // To get TaskTraits for tasks that have more precise traits: provide any |
| 217 | // combination of ValidTrait's as arguments to this constructor. |
| 218 | // |
| 219 | // Note: When posting to well-known threads (e.g. UI/IO), default traits are |
| 220 | // almost always what you want unless you know for sure the task being posted |
| 221 | // has no explicit/implicit ordering dependency with anything else running at |
| 222 | // default (USER_BLOCKING) priority. |
| 223 | // |
| 224 | // E.g. |
| 225 | // constexpr base::TaskTraits default_traits = {}; |
| 226 | // constexpr base::TaskTraits user_visible_traits = { |
| 227 | // base::TaskPriority::USER_VISIBLE}; |
| 228 | // constexpr base::TaskTraits user_visible_may_block_traits = { |
| 229 | // base::TaskPriority::USER_VISIBLE, base::MayBlock() |
| 230 | // }; |
| 231 | // constexpr base::TaskTraits other_user_visible_may_block_traits = { |
| 232 | // base::MayBlock(), base::TaskPriority::USER_VISIBLE |
| 233 | // }; |
| 234 | template <class... ArgTypes, |
| 235 | class CheckArgumentsAreValid = std::enable_if_t< |
| 236 | trait_helpers::AreValidTraits<ValidTrait, ArgTypes...>::value || |
| 237 | trait_helpers::AreValidTraitsForExtension<ArgTypes...>::value>> |
| 238 | constexpr TaskTraits(ArgTypes... args) |
| 239 | : extension_(trait_helpers::GetTaskTraitsExtension( |
| 240 | trait_helpers::AreValidTraits<ValidTrait, ArgTypes...>{}, |
| 241 | args...)), |
| 242 | priority_( |
| 243 | trait_helpers::GetEnum<TaskPriority, TaskPriority::USER_BLOCKING>( |
| 244 | args...)), |
| 245 | shutdown_behavior_( |
| 246 | static_cast<uint8_t>( |
| 247 | trait_helpers::GetEnum<TaskShutdownBehavior, |
| 248 | TaskShutdownBehavior::SKIP_ON_SHUTDOWN>( |
| 249 | args...)) | |
| 250 | (trait_helpers::HasTrait<TaskShutdownBehavior, ArgTypes...>() |
| 251 | ? kIsExplicitFlag |
| 252 | : 0)), |
| 253 | thread_policy_( |
| 254 | static_cast<uint8_t>( |
| 255 | trait_helpers::GetEnum<ThreadPolicy, |
| 256 | ThreadPolicy::PREFER_BACKGROUND>( |
| 257 | args...)) | |
| 258 | (trait_helpers::HasTrait<ThreadPolicy, ArgTypes...>() |
| 259 | ? kIsExplicitFlag |
| 260 | : 0)), |
| 261 | may_block_(trait_helpers::HasTrait<MayBlock, ArgTypes...>()), |
| 262 | with_base_sync_primitives_( |
| 263 | trait_helpers::HasTrait<WithBaseSyncPrimitives, ArgTypes...>()), |
| 264 | use_thread_pool_(trait_helpers::HasTrait<ThreadPool, ArgTypes...>()) {} |
| 265 |
| 266 | constexpr TaskTraits(const TaskTraits& other) = default; |
| 267 | TaskTraits& operator=(const TaskTraits& other) = default; |
| 268 |
| 269 | // TODO(eseckler): Default the comparison operator once C++20 arrives. |
| 270 | bool operator==(const TaskTraits& other) const { |
| 271 | static_assert(sizeof(TaskTraits) == 15, |
| 272 | "Update comparison operator when TaskTraits change"); |
| 273 | return extension_ == other.extension_ && priority_ == other.priority_ && |
| 274 | shutdown_behavior_ == other.shutdown_behavior_ && |
| 275 | thread_policy_ == other.thread_policy_ && |
| 276 | may_block_ == other.may_block_ && |
| 277 | with_base_sync_primitives_ == other.with_base_sync_primitives_ && |
| 278 | use_thread_pool_ == other.use_thread_pool_; |
| 279 | } |
| 280 |
| 281 | // Sets the priority of tasks with these traits to |priority|. |
| 282 | void UpdatePriority(TaskPriority priority) { priority_ = priority; } |
| 283 |
| 284 | // Returns the priority of tasks with these traits. |
| 285 | constexpr TaskPriority priority() const { return priority_; } |
| 286 |
| 287 | // Returns true if the shutdown behavior was set explicitly. |
| 288 | constexpr bool shutdown_behavior_set_explicitly() const { |
| 289 | return shutdown_behavior_ & kIsExplicitFlag; |
| 290 | } |
| 291 |
| 292 | // Returns the shutdown behavior of tasks with these traits. |
| 293 | constexpr TaskShutdownBehavior shutdown_behavior() const { |
| 294 | return static_cast<TaskShutdownBehavior>(shutdown_behavior_ & |
| 295 | ~kIsExplicitFlag); |
| 296 | } |
| 297 |
| 298 | // Returns true if the thread policy was set explicitly. |
| 299 | constexpr bool thread_policy_set_explicitly() const { |
| 300 | return thread_policy_ & kIsExplicitFlag; |
| 301 | } |
| 302 |
| 303 | // Returns the thread policy of tasks with these traits. |
| 304 | constexpr ThreadPolicy thread_policy() const { |
| 305 | return static_cast<ThreadPolicy>(thread_policy_ & ~kIsExplicitFlag); |
| 306 | } |
| 307 |
| 308 | // Returns true if tasks with these traits may block. |
| 309 | constexpr bool may_block() const { return may_block_; } |
| 310 |
| 311 | // Returns true if tasks with these traits may use base/ sync primitives. |
| 312 | constexpr bool with_base_sync_primitives() const { |
| 313 | return with_base_sync_primitives_; |
| 314 | } |
| 315 |
| 316 | // Returns true if tasks with these traits execute on the thread pool. |
| 317 | constexpr bool use_thread_pool() const { return use_thread_pool_; } |
| 318 |
| 319 | uint8_t extension_id() const { return extension_.extension_id; } |
| 320 |
| 321 | // Access the extension data by parsing it into the provided extension type. |
| 322 | // See task_traits_extension.h for requirements on the extension type. |
| 323 | template <class TaskTraitsExtension> |
| 324 | const TaskTraitsExtension GetExtension() const { |
| 325 | DCHECK_EQ(TaskTraitsExtension::kExtensionId, extension_.extension_id); |
| 326 | return TaskTraitsExtension::Parse(extension_); |
| 327 | } |
| 328 |
| 329 | private: |
| 330 | friend PostTaskAndroid; |
| 331 |
| 332 | // For use by PostTaskAndroid. |
| 333 | TaskTraits(TaskPriority priority, |
| 334 | bool may_block, |
| 335 | bool use_thread_pool, |
| 336 | TaskTraitsExtensionStorage extension) |
| 337 | : extension_(extension), |
| 338 | priority_(priority), |
| 339 | shutdown_behavior_( |
| 340 | static_cast<uint8_t>(TaskShutdownBehavior::SKIP_ON_SHUTDOWN)), |
| 341 | thread_policy_(static_cast<uint8_t>(ThreadPolicy::PREFER_BACKGROUND)), |
| 342 | may_block_(may_block), |
| 343 | with_base_sync_primitives_(false), |
| 344 | use_thread_pool_(use_thread_pool) { |
| 345 | static_assert(sizeof(TaskTraits) == 15, "Keep this constructor up to date"); |
| 346 |
| 347 | // Java is expected to provide an explicit destination. See TODO in |
| 348 | // TaskTraits.java to move towards API-as-a-destination there as well. |
| 349 | const bool has_extension = |
| 350 | (extension_.extension_id != |
| 351 | TaskTraitsExtensionStorage::kInvalidExtensionId); |
| 352 | DCHECK(use_thread_pool_ ^ has_extension) |
| 353 | << "Traits must explicitly specify a destination (e.g. ThreadPool or a " |
| 354 | "named thread like BrowserThread)"; |
| 355 | } |
| 356 |
| 357 | // This bit is set in |priority_|, |shutdown_behavior_| and |thread_policy_| |
| 358 | // when the value was set explicitly. |
| 359 | static constexpr uint8_t kIsExplicitFlag = 0x80; |
| 360 |
| 361 | // Ordered for packing. |
| 362 | TaskTraitsExtensionStorage extension_; |
| 363 | TaskPriority priority_; |
| 364 | uint8_t shutdown_behavior_; |
| 365 | uint8_t thread_policy_; |
| 366 | bool may_block_; |
| 367 | bool with_base_sync_primitives_; |
| 368 | bool use_thread_pool_; |
| 369 | }; |
| 370 |
| 371 | // Returns string literals for the enums defined in this file. These methods |
| 372 | // should only be used for tracing and debugging. |
| 373 | BASE_EXPORT const char* TaskPriorityToString(TaskPriority task_priority); |
| 374 | BASE_EXPORT const char* TaskShutdownBehaviorToString( |
| 375 | TaskShutdownBehavior task_priority); |
| 376 |
| 377 | // Stream operators so that the enums defined in this file can be used in |
| 378 | // DCHECK and EXPECT statements. |
| 379 | BASE_EXPORT std::ostream& operator<<(std::ostream& os, |
| 380 | const TaskPriority& shutdown_behavior); |
| 381 | BASE_EXPORT std::ostream& operator<<( |
| 382 | std::ostream& os, |
| 383 | const TaskShutdownBehavior& shutdown_behavior); |
| 384 |
| 385 | } // namespace base |
| 386 |
| 387 | #endif // BASE_TASK_TASK_TRAITS_H_ |
| 388 |