blob: 7ae85e6dcfa8cdfe36720d8ec81653a86f2bf48a [file] [log] [blame]
gab6b48dd12016-05-11 08:17:01 +09001// 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"
gabf86498c2017-03-02 09:46:14 +09009#include "base/callback_helpers.h"
gab6b48dd12016-05-11 08:17:01 +090010#include "base/macros.h"
11#include "base/memory/ref_counted.h"
fdoraya9033812016-06-10 07:55:06 +090012#include "base/single_thread_task_runner.h"
gab6b48dd12016-05-11 08:17:01 +090013
14namespace base {
15
gab6b48dd12016-05-11 08:17:01 +090016// ThreadTaskRunnerHandle stores a reference to a thread's TaskRunner
17// in thread-local storage. Callers can then retrieve the TaskRunner
18// for the current thread by calling ThreadTaskRunnerHandle::Get().
19// At most one TaskRunner may be bound to each thread at a time.
20// Prefer SequenceTaskRunnerHandle to this unless thread affinity is required.
21class BASE_EXPORT ThreadTaskRunnerHandle {
22 public:
23 // Gets the SingleThreadTaskRunner for the current thread.
24 static scoped_refptr<SingleThreadTaskRunner> Get();
25
26 // Returns true if the SingleThreadTaskRunner is already created for
27 // the current thread.
28 static bool IsSet();
29
gabf86498c2017-03-02 09:46:14 +090030 // Overrides ThreadTaskRunnerHandle::Get()'s |task_runner_| to point at
31 // |overriding_task_runner| until the returned ScopedClosureRunner goes out of
32 // scope (instantiates a ThreadTaskRunnerHandle for that scope if |!IsSet()|).
33 // Nested overrides are allowed but callers must ensure the
34 // ScopedClosureRunners expire in LIFO (stack) order. Note: nesting
35 // ThreadTaskRunnerHandles isn't generally desired but it's useful in unit
36 // tests where multiple task runners can share the main thread for simplicity
37 // and determinism.
38 static ScopedClosureRunner OverrideForTesting(
39 scoped_refptr<SingleThreadTaskRunner> overriding_task_runner);
40
gab6b48dd12016-05-11 08:17:01 +090041 // Binds |task_runner| to the current thread. |task_runner| must belong
42 // to the current thread for this to succeed.
43 explicit ThreadTaskRunnerHandle(
44 scoped_refptr<SingleThreadTaskRunner> task_runner);
45 ~ThreadTaskRunnerHandle();
46
47 private:
48 scoped_refptr<SingleThreadTaskRunner> task_runner_;
49
50 DISALLOW_COPY_AND_ASSIGN(ThreadTaskRunnerHandle);
51};
52
53} // namespace base
54
55#endif // BASE_THREADING_THREAD_TASK_RUNNER_HANDLE_H_