blob: 569b747e6800ee02559ca144b9f3ced33669203f [file] [log] [blame]
Jordan Baylesb0c191e2019-03-26 15:49:57 -07001// 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
Jordan Baylesa26582d2019-07-10 14:44:58 -07005#ifndef PLATFORM_IMPL_TASK_RUNNER_H_
6#define PLATFORM_IMPL_TASK_RUNNER_H_
Jordan Baylesb0c191e2019-03-26 15:49:57 -07007
8#include <atomic>
9#include <condition_variable> // NOLINT
Yuri Wiitalab929b832019-06-05 17:13:15 -070010#include <map>
Jordan Baylesb0c191e2019-03-26 15:49:57 -070011#include <memory>
Ryan Keanea973b512019-07-29 15:50:39 -070012#include <mutex> // NOLINT
Max Yakimakhabf567dc2019-09-20 13:37:04 -070013#include <thread>
Jordan Baylesb0c191e2019-03-26 15:49:57 -070014#include <utility>
15#include <vector>
16
17#include "absl/base/thread_annotations.h"
18#include "absl/types/optional.h"
Ryan Keane230920e2019-08-29 13:21:40 -070019#include "platform/api/task_runner.h"
Jordan Baylesb0c191e2019-03-26 15:49:57 -070020#include "platform/api/time.h"
Ryan Keaneefab2ed2019-07-22 12:36:53 -070021#include "platform/api/trace_logging.h"
Jordan Baylesa26582d2019-07-10 14:44:58 -070022#include "platform/base/error.h"
Jordan Baylesb0c191e2019-03-26 15:49:57 -070023
24namespace openscreen {
25namespace platform {
26
btolsch4051e722019-06-07 16:15:17 -070027class TaskRunnerImpl final : public TaskRunner {
Jordan Baylesb0c191e2019-03-26 15:49:57 -070028 public:
btolsch4051e722019-06-07 16:15:17 -070029 using Task = TaskRunner::Task;
30
btolschd94fe622019-05-09 14:21:40 -070031 class TaskWaiter {
32 public:
33 virtual ~TaskWaiter() = default;
34
35 // These calls should be thread-safe. The absolute minimum is that
36 // OnTaskPosted must be safe to call from another thread while this is
37 // inside WaitForTaskToBePosted. NOTE: There may be spurious wakeups from
38 // WaitForTaskToBePosted depending on whether the specific implementation
39 // chooses to clear queued WakeUps before entering WaitForTaskToBePosted.
40
41 // Blocks until some event occurs, which means new tasks may have been
42 // posted. Wait may only block up to |timeout| where 0 means don't block at
43 // all (not block forever).
44 virtual Error WaitForTaskToBePosted(Clock::duration timeout) = 0;
45
46 // If a WaitForTaskToBePosted call is currently blocking, unblock it
47 // immediately.
48 virtual void OnTaskPosted() = 0;
49 };
50
51 explicit TaskRunnerImpl(
52 platform::ClockNowFunctionPtr now_function,
53 TaskWaiter* event_waiter = nullptr,
54 Clock::duration waiter_timeout = std::chrono::milliseconds(100));
Jordan Baylesb0c191e2019-03-26 15:49:57 -070055
56 // TaskRunner overrides
Yuri Wiitalab929b832019-06-05 17:13:15 -070057 ~TaskRunnerImpl() final;
58 void PostPackagedTask(Task task) final;
59 void PostPackagedTaskWithDelay(Task task, Clock::duration delay) final;
Max Yakimakhabf567dc2019-09-20 13:37:04 -070060 bool IsRunningOnTaskRunner() final;
Jordan Baylesb0c191e2019-03-26 15:49:57 -070061
Jordan Baylesa8e96772019-04-08 10:53:54 -070062 // Tasks will only be executed if RunUntilStopped has been called, and
btolsch4051e722019-06-07 16:15:17 -070063 // RequestStopSoon has not. Important note: TaskRunner does NOT do any
Jordan Baylesa8e96772019-04-08 10:53:54 -070064 // threading, so calling "RunUntilStopped()" will block whatever thread you
65 // are calling it on.
Jordan Baylesb0c191e2019-03-26 15:49:57 -070066 void RunUntilStopped();
Jordan Baylesa8e96772019-04-08 10:53:54 -070067
btolsch4051e722019-06-07 16:15:17 -070068 // Thread-safe method for requesting the TaskRunner to stop running. This sets
69 // a flag that will get checked in the run loop, typically after completing
70 // the current task.
Jordan Baylesb0c191e2019-03-26 15:49:57 -070071 void RequestStopSoon();
72
73 // Execute all tasks immediately, useful for testing only. Note: this method
74 // will schedule any delayed tasks that are ready to run, but does not block
75 // waiting for delayed tasks to become eligible.
76 void RunUntilIdleForTesting();
77
78 private:
Ryan Keane1d9c0c42019-07-29 15:22:19 -070079#ifndef TRACE_FORCE_DISABLE
Ryan Keaneefab2ed2019-07-22 12:36:53 -070080 // Wrapper around a Task used to store the TraceId Metadata along with the
81 // task itself, and to set the current TraceIdHierarchy before executing the
82 // task.
83 class TaskWithMetadata {
84 public:
Ryan Keane1d9c0c42019-07-29 15:22:19 -070085 // NOTE: 'explicit' keyword omitted so that conversion construtor can be
86 // used. This simplifies switching between 'Task' and 'TaskWithMetadata'
87 // based on the compilation flag.
88 TaskWithMetadata(Task task)
89 : task_(std::move(task)), trace_ids_(TRACE_HIERARCHY){};
Ryan Keaneefab2ed2019-07-22 12:36:53 -070090
Ryan Keane1d9c0c42019-07-29 15:22:19 -070091 void operator()() {
92 TRACE_SET_HIERARCHY(trace_ids_);
93 std::move(task_)();
94 }
Ryan Keaneefab2ed2019-07-22 12:36:53 -070095
96 private:
97 Task task_;
98 TraceIdHierarchy trace_ids_;
99 };
Ryan Keane1d9c0c42019-07-29 15:22:19 -0700100#else // TRACE_FORCE_DISABLE defined
101 using TaskWithMetadata = Task;
102#endif // TRACE_FORCE_DISABLE
Ryan Keaneefab2ed2019-07-22 12:36:53 -0700103
Jordan Baylesa8e96772019-04-08 10:53:54 -0700104 // Run all tasks already in the task queue. If the queue is empty, wait for
105 // either (1) a delayed task to become available, or (2) a task to be added
106 // to the queue.
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700107 void RunCurrentTasksBlocking();
Jordan Baylesa8e96772019-04-08 10:53:54 -0700108
109 // Run tasks already in the queue, for testing. If the queue is empty, this
110 // method does not block but instead returns immediately.
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700111 void RunCurrentTasksForTesting();
112
Jordan Baylesa8e96772019-04-08 10:53:54 -0700113 // Loop method that runs tasks in the current thread, until the
114 // RequestStopSoon method is called.
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700115 void RunTasksUntilStopped();
116
117 // Look at all tasks in the delayed task queue, then schedule them if the
118 // minimum delay time has elapsed.
119 void ScheduleDelayedTasks();
120
Jordan Bayles5d72bc22019-04-09 13:33:52 -0700121 // Look at the current state of the TaskRunner and determine if the run loop
122 // should be woken up
123 bool ShouldWakeUpRunLoop();
124
Jordan Baylesa8e96772019-04-08 10:53:54 -0700125 // Takes the task_mutex_ lock, returning immediately if work is available. If
126 // no work is available, this places the task running thread into a waiting
127 // state until we stop running or work is available.
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700128 std::unique_lock<std::mutex> WaitForWorkAndAcquireLock();
129
130 const platform::ClockNowFunctionPtr now_function_;
131
132 // Atomic so that we can perform atomic exchanges.
133 std::atomic_bool is_running_;
134
Yuri Wiitalab929b832019-06-05 17:13:15 -0700135 // This mutex is used for |tasks_| and |delayed_tasks_|, and also for
136 // notifying the run loop to wake up when it is waiting for a task to be added
137 // to the queue in |run_loop_wakeup_|.
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700138 std::mutex task_mutex_;
Ryan Keaneefab2ed2019-07-22 12:36:53 -0700139 std::vector<TaskWithMetadata> tasks_ GUARDED_BY(task_mutex_);
140 std::multimap<Clock::time_point, TaskWithMetadata> delayed_tasks_
141 GUARDED_BY(task_mutex_);
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700142
btolschd94fe622019-05-09 14:21:40 -0700143 // When |task_waiter_| is nullptr, |run_loop_wakeup_| is used for sleeping the
144 // task runner. Otherwise, |run_loop_wakeup_| isn't used and |task_waiter_|
145 // is used instead (along with |waiter_timeout_|).
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700146 std::condition_variable run_loop_wakeup_;
btolschd94fe622019-05-09 14:21:40 -0700147 TaskWaiter* const task_waiter_;
148 Clock::duration waiter_timeout_;
Yuri Wiitalab929b832019-06-05 17:13:15 -0700149
150 // To prevent excessive re-allocation of the underlying array of the |tasks_|
151 // vector, use an A/B vector-swap mechanism. |running_tasks_| starts out
152 // empty, and is swapped with |tasks_| when it is time to run the Tasks.
Ryan Keaneefab2ed2019-07-22 12:36:53 -0700153 std::vector<TaskWithMetadata> running_tasks_;
Ryan Keane32c88d02019-07-02 18:46:14 -0700154
Max Yakimakhabf567dc2019-09-20 13:37:04 -0700155 std::thread::id task_runner_thread_id_;
156
Ryan Keane32c88d02019-07-02 18:46:14 -0700157 OSP_DISALLOW_COPY_AND_ASSIGN(TaskRunnerImpl);
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700158};
159} // namespace platform
160} // namespace openscreen
161
Jordan Baylesa26582d2019-07-10 14:44:58 -0700162#endif // PLATFORM_IMPL_TASK_RUNNER_H_