thread_task_runner_handle.h 2.5 KB

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