Scott Graham | 6696211 | 2018-06-08 12:42:08 -0700 | [diff] [blame] | 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 | |
| 5 | #ifndef BASE_THREADING_THREAD_TASK_RUNNER_HANDLE_H_ |
| 6 | #define BASE_THREADING_THREAD_TASK_RUNNER_HANDLE_H_ |
| 7 | |
| 8 | #include "base/base_export.h" |
| 9 | #include "base/callback_helpers.h" |
| 10 | #include "base/compiler_specific.h" |
| 11 | #include "base/macros.h" |
| 12 | #include "base/memory/ref_counted.h" |
| 13 | #include "base/single_thread_task_runner.h" |
| 14 | |
| 15 | namespace base { |
| 16 | |
| 17 | // ThreadTaskRunnerHandle stores a reference to a thread's TaskRunner |
| 18 | // in thread-local storage. Callers can then retrieve the TaskRunner |
| 19 | // for the current thread by calling ThreadTaskRunnerHandle::Get(). |
| 20 | // At most one TaskRunner may be bound to each thread at a time. |
| 21 | // Prefer SequencedTaskRunnerHandle to this unless thread affinity is required. |
| 22 | class BASE_EXPORT ThreadTaskRunnerHandle { |
| 23 | public: |
| 24 | // Gets the SingleThreadTaskRunner for the current thread. |
| 25 | static scoped_refptr<SingleThreadTaskRunner> Get(); |
| 26 | |
| 27 | // Returns true if the SingleThreadTaskRunner is already created for |
| 28 | // the current thread. |
| 29 | static bool IsSet(); |
| 30 | |
| 31 | // Overrides ThreadTaskRunnerHandle::Get()'s |task_runner_| to point at |
| 32 | // |overriding_task_runner| until the returned ScopedClosureRunner goes out of |
| 33 | // scope (instantiates a ThreadTaskRunnerHandle for that scope if |!IsSet()|). |
| 34 | // Nested overrides are allowed but callers must ensure the |
| 35 | // ScopedClosureRunners expire in LIFO (stack) order. Note: nesting |
| 36 | // ThreadTaskRunnerHandles isn't generally desired but it's useful in unit |
| 37 | // tests where multiple task runners can share the main thread for simplicity |
| 38 | // and determinism. |
| 39 | static ScopedClosureRunner OverrideForTesting( |
| 40 | scoped_refptr<SingleThreadTaskRunner> overriding_task_runner) |
| 41 | WARN_UNUSED_RESULT; |
| 42 | |
| 43 | // Binds |task_runner| to the current thread. |task_runner| must belong |
| 44 | // to the current thread for this to succeed. |
| 45 | explicit ThreadTaskRunnerHandle( |
| 46 | scoped_refptr<SingleThreadTaskRunner> task_runner); |
| 47 | ~ThreadTaskRunnerHandle(); |
| 48 | |
| 49 | private: |
| 50 | scoped_refptr<SingleThreadTaskRunner> task_runner_; |
| 51 | |
| 52 | DISALLOW_COPY_AND_ASSIGN(ThreadTaskRunnerHandle); |
| 53 | }; |
| 54 | |
| 55 | } // namespace base |
| 56 | |
| 57 | #endif // BASE_THREADING_THREAD_TASK_RUNNER_HANDLE_H_ |