blob: d450745aee03a6888546b59a6ff7d439030e50a9 [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
Jordan Baylesb0c191e2019-03-26 15:49:57 -07008#include <condition_variable> // NOLINT
Yuri Wiitalab929b832019-06-05 17:13:15 -07009#include <map>
Jordan Baylesb0c191e2019-03-26 15:49:57 -070010#include <memory>
Ryan Keanea973b512019-07-29 15:50:39 -070011#include <mutex> // NOLINT
Max Yakimakhabf567dc2019-09-20 13:37:04 -070012#include <thread>
Jordan Baylesb0c191e2019-03-26 15:49:57 -070013#include <utility>
14#include <vector>
15
16#include "absl/base/thread_annotations.h"
17#include "absl/types/optional.h"
Ryan Keane230920e2019-08-29 13:21:40 -070018#include "platform/api/task_runner.h"
Jordan Baylesb0c191e2019-03-26 15:49:57 -070019#include "platform/api/time.h"
Ryan Keaneefab2ed2019-07-22 12:36:53 -070020#include "platform/api/trace_logging.h"
Jordan Baylesa26582d2019-07-10 14:44:58 -070021#include "platform/base/error.h"
Jordan Baylesb0c191e2019-03-26 15:49:57 -070022
23namespace openscreen {
24namespace platform {
25
btolsch4051e722019-06-07 16:15:17 -070026class TaskRunnerImpl final : public TaskRunner {
Jordan Baylesb0c191e2019-03-26 15:49:57 -070027 public:
btolsch4051e722019-06-07 16:15:17 -070028 using Task = TaskRunner::Task;
29
btolschd94fe622019-05-09 14:21:40 -070030 class TaskWaiter {
31 public:
32 virtual ~TaskWaiter() = default;
33
34 // These calls should be thread-safe. The absolute minimum is that
35 // OnTaskPosted must be safe to call from another thread while this is
36 // inside WaitForTaskToBePosted. NOTE: There may be spurious wakeups from
37 // WaitForTaskToBePosted depending on whether the specific implementation
38 // chooses to clear queued WakeUps before entering WaitForTaskToBePosted.
39
40 // Blocks until some event occurs, which means new tasks may have been
41 // posted. Wait may only block up to |timeout| where 0 means don't block at
42 // all (not block forever).
43 virtual Error WaitForTaskToBePosted(Clock::duration timeout) = 0;
44
45 // If a WaitForTaskToBePosted call is currently blocking, unblock it
46 // immediately.
47 virtual void OnTaskPosted() = 0;
48 };
49
50 explicit TaskRunnerImpl(
51 platform::ClockNowFunctionPtr now_function,
52 TaskWaiter* event_waiter = nullptr,
53 Clock::duration waiter_timeout = std::chrono::milliseconds(100));
Jordan Baylesb0c191e2019-03-26 15:49:57 -070054
55 // TaskRunner overrides
Yuri Wiitalab929b832019-06-05 17:13:15 -070056 ~TaskRunnerImpl() final;
57 void PostPackagedTask(Task task) final;
58 void PostPackagedTaskWithDelay(Task task, Clock::duration delay) final;
Max Yakimakhabf567dc2019-09-20 13:37:04 -070059 bool IsRunningOnTaskRunner() final;
Jordan Baylesb0c191e2019-03-26 15:49:57 -070060
Yuri Wiitalac05ada22019-09-24 14:25:19 -070061 // Blocks the current thread, executing tasks from the queue with the desired
62 // timing; and does not return until some time after RequestStopSoon() is
63 // called.
Jordan Baylesb0c191e2019-03-26 15:49:57 -070064 void RunUntilStopped();
Jordan Baylesa8e96772019-04-08 10:53:54 -070065
Yuri Wiitalac05ada22019-09-24 14:25:19 -070066 // Thread-safe method for requesting the TaskRunner to stop running after all
67 // non-delayed tasks in the queue have run. This behavior allows final
68 // clean-up tasks to be executed before the TaskRunner stops.
69 //
70 // If any non-delayed tasks post additional non-delayed tasks, those will be
71 // run as well before returning.
Jordan Baylesb0c191e2019-03-26 15:49:57 -070072 void RequestStopSoon();
73
Jordan Baylesb0c191e2019-03-26 15:49:57 -070074 private:
Ryan Keane1d9c0c42019-07-29 15:22:19 -070075#ifndef TRACE_FORCE_DISABLE
Ryan Keaneefab2ed2019-07-22 12:36:53 -070076 // Wrapper around a Task used to store the TraceId Metadata along with the
77 // task itself, and to set the current TraceIdHierarchy before executing the
78 // task.
79 class TaskWithMetadata {
80 public:
Ryan Keane1d9c0c42019-07-29 15:22:19 -070081 // NOTE: 'explicit' keyword omitted so that conversion construtor can be
82 // used. This simplifies switching between 'Task' and 'TaskWithMetadata'
83 // based on the compilation flag.
84 TaskWithMetadata(Task task)
85 : task_(std::move(task)), trace_ids_(TRACE_HIERARCHY){};
Ryan Keaneefab2ed2019-07-22 12:36:53 -070086
Ryan Keane1d9c0c42019-07-29 15:22:19 -070087 void operator()() {
88 TRACE_SET_HIERARCHY(trace_ids_);
89 std::move(task_)();
90 }
Ryan Keaneefab2ed2019-07-22 12:36:53 -070091
92 private:
93 Task task_;
94 TraceIdHierarchy trace_ids_;
95 };
Ryan Keane1d9c0c42019-07-29 15:22:19 -070096#else // TRACE_FORCE_DISABLE defined
97 using TaskWithMetadata = Task;
98#endif // TRACE_FORCE_DISABLE
Ryan Keaneefab2ed2019-07-22 12:36:53 -070099
Yuri Wiitalac05ada22019-09-24 14:25:19 -0700100 // If necessary, wait for either (1) a delayed task to become available, or
101 // (2) a task to be added to the queue; and then run all runnable tasks.
102 void RunTasksAfterWaiting();
Jordan Baylesa8e96772019-04-08 10:53:54 -0700103
Yuri Wiitalac05ada22019-09-24 14:25:19 -0700104 // Helper that runs all tasks in |running_tasks_| and then clears it.
105 void RunRunnableTasks();
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700106
107 // Look at all tasks in the delayed task queue, then schedule them if the
108 // minimum delay time has elapsed.
109 void ScheduleDelayedTasks();
110
Jordan Bayles5d72bc22019-04-09 13:33:52 -0700111 // Look at the current state of the TaskRunner and determine if the run loop
112 // should be woken up
113 bool ShouldWakeUpRunLoop();
114
Jordan Baylesa8e96772019-04-08 10:53:54 -0700115 // Takes the task_mutex_ lock, returning immediately if work is available. If
116 // no work is available, this places the task running thread into a waiting
117 // state until we stop running or work is available.
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700118 std::unique_lock<std::mutex> WaitForWorkAndAcquireLock();
119
120 const platform::ClockNowFunctionPtr now_function_;
121
Yuri Wiitalac05ada22019-09-24 14:25:19 -0700122 // Flag that indicates whether the task runner loop should continue. This is
123 // only meant to be read/written on the thread executing RunUntilStopped().
124 bool is_running_;
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700125
Yuri Wiitalab929b832019-06-05 17:13:15 -0700126 // This mutex is used for |tasks_| and |delayed_tasks_|, and also for
127 // notifying the run loop to wake up when it is waiting for a task to be added
128 // to the queue in |run_loop_wakeup_|.
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700129 std::mutex task_mutex_;
Ryan Keaneefab2ed2019-07-22 12:36:53 -0700130 std::vector<TaskWithMetadata> tasks_ GUARDED_BY(task_mutex_);
131 std::multimap<Clock::time_point, TaskWithMetadata> delayed_tasks_
132 GUARDED_BY(task_mutex_);
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700133
btolschd94fe622019-05-09 14:21:40 -0700134 // When |task_waiter_| is nullptr, |run_loop_wakeup_| is used for sleeping the
135 // task runner. Otherwise, |run_loop_wakeup_| isn't used and |task_waiter_|
136 // is used instead (along with |waiter_timeout_|).
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700137 std::condition_variable run_loop_wakeup_;
btolschd94fe622019-05-09 14:21:40 -0700138 TaskWaiter* const task_waiter_;
139 Clock::duration waiter_timeout_;
Yuri Wiitalab929b832019-06-05 17:13:15 -0700140
141 // To prevent excessive re-allocation of the underlying array of the |tasks_|
142 // vector, use an A/B vector-swap mechanism. |running_tasks_| starts out
143 // empty, and is swapped with |tasks_| when it is time to run the Tasks.
Ryan Keaneefab2ed2019-07-22 12:36:53 -0700144 std::vector<TaskWithMetadata> running_tasks_;
Ryan Keane32c88d02019-07-02 18:46:14 -0700145
Max Yakimakhabf567dc2019-09-20 13:37:04 -0700146 std::thread::id task_runner_thread_id_;
147
Ryan Keane32c88d02019-07-02 18:46:14 -0700148 OSP_DISALLOW_COPY_AND_ASSIGN(TaskRunnerImpl);
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700149};
150} // namespace platform
151} // namespace openscreen
152
Jordan Baylesa26582d2019-07-10 14:44:58 -0700153#endif // PLATFORM_IMPL_TASK_RUNNER_H_