blob: 65dfbf5ea3463773f28839b9e9f6e38bac6fdf2b [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>
Jordan Baylesc9201dd2020-06-02 15:51:31 -070011#include <mutex>
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"
Jordan Baylesa26582d2019-07-10 14:44:58 -070020#include "platform/base/error.h"
Yuri Wiitala8e6db3b2019-11-20 11:20:54 -080021#include "util/trace_logging.h"
Jordan Baylesb0c191e2019-03-26 15:49:57 -070022
23namespace openscreen {
Jordan Baylesb0c191e2019-03-26 15:49:57 -070024
btolsch4051e722019-06-07 16:15:17 -070025class TaskRunnerImpl final : public TaskRunner {
Jordan Baylesb0c191e2019-03-26 15:49:57 -070026 public:
btolsch4051e722019-06-07 16:15:17 -070027 using Task = TaskRunner::Task;
28
btolschd94fe622019-05-09 14:21:40 -070029 class TaskWaiter {
30 public:
31 virtual ~TaskWaiter() = default;
32
33 // These calls should be thread-safe. The absolute minimum is that
34 // OnTaskPosted must be safe to call from another thread while this is
35 // inside WaitForTaskToBePosted. NOTE: There may be spurious wakeups from
36 // WaitForTaskToBePosted depending on whether the specific implementation
37 // chooses to clear queued WakeUps before entering WaitForTaskToBePosted.
38
39 // Blocks until some event occurs, which means new tasks may have been
40 // posted. Wait may only block up to |timeout| where 0 means don't block at
41 // all (not block forever).
42 virtual Error WaitForTaskToBePosted(Clock::duration timeout) = 0;
43
44 // If a WaitForTaskToBePosted call is currently blocking, unblock it
45 // immediately.
46 virtual void OnTaskPosted() = 0;
47 };
48
49 explicit TaskRunnerImpl(
Yuri Wiitala2b02e322019-12-03 16:59:40 -080050 ClockNowFunctionPtr now_function,
btolschd94fe622019-05-09 14:21:40 -070051 TaskWaiter* event_waiter = nullptr,
52 Clock::duration waiter_timeout = std::chrono::milliseconds(100));
Jordan Baylesb0c191e2019-03-26 15:49:57 -070053
54 // TaskRunner overrides
Yuri Wiitalab929b832019-06-05 17:13:15 -070055 ~TaskRunnerImpl() final;
56 void PostPackagedTask(Task task) final;
57 void PostPackagedTaskWithDelay(Task task, Clock::duration delay) final;
Max Yakimakhabf567dc2019-09-20 13:37:04 -070058 bool IsRunningOnTaskRunner() final;
Jordan Baylesb0c191e2019-03-26 15:49:57 -070059
Yuri Wiitalac05ada22019-09-24 14:25:19 -070060 // Blocks the current thread, executing tasks from the queue with the desired
61 // timing; and does not return until some time after RequestStopSoon() is
62 // called.
Jordan Baylesb0c191e2019-03-26 15:49:57 -070063 void RunUntilStopped();
Jordan Baylesa8e96772019-04-08 10:53:54 -070064
Yuri Wiitala341085a2020-03-11 17:13:54 -070065 // Blocks the current thread, executing tasks from the queue with the desired
66 // timing; and does not return until some time after the current process is
67 // signaled with SIGINT or SIGTERM, or after RequestStopSoon() is called.
68 void RunUntilSignaled();
69
Yuri Wiitalac05ada22019-09-24 14:25:19 -070070 // Thread-safe method for requesting the TaskRunner to stop running after all
71 // non-delayed tasks in the queue have run. This behavior allows final
72 // clean-up tasks to be executed before the TaskRunner stops.
73 //
74 // If any non-delayed tasks post additional non-delayed tasks, those will be
75 // run as well before returning.
Jordan Baylesb0c191e2019-03-26 15:49:57 -070076 void RequestStopSoon();
77
Jordan Baylesb0c191e2019-03-26 15:49:57 -070078 private:
Yuri Wiitala8e6db3b2019-11-20 11:20:54 -080079#if defined(ENABLE_TRACE_LOGGING)
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.
mark a. foltzb4e53be2020-05-28 11:42:36 -070088 TaskWithMetadata(Task task) // NOLINT
Yuri Wiitalaca24ee52019-12-05 16:51:42 -080089 : 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 };
Yuri Wiitala8e6db3b2019-11-20 11:20:54 -0800100#else // !defined(ENABLE_TRACE_LOGGING)
Ryan Keane1d9c0c42019-07-29 15:22:19 -0700101 using TaskWithMetadata = Task;
Yuri Wiitala8e6db3b2019-11-20 11:20:54 -0800102#endif // defined(ENABLE_TRACE_LOGGING)
Ryan Keaneefab2ed2019-07-22 12:36:53 -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
Yuri Wiitala71a84bc2019-09-25 12:00:23 -0700111 // Transfers all ready-to-run tasks from |tasks_| to |running_tasks_|. If
112 // there are no ready-to-run tasks, and |is_running_| is true, this method
113 // will block waiting for new tasks. Returns true if any tasks were
114 // transferred.
115 bool GrabMoreRunnableTasks();
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700116
Yuri Wiitala2b02e322019-12-03 16:59:40 -0800117 const ClockNowFunctionPtr now_function_;
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700118
Yuri Wiitalac05ada22019-09-24 14:25:19 -0700119 // Flag that indicates whether the task runner loop should continue. This is
120 // only meant to be read/written on the thread executing RunUntilStopped().
121 bool is_running_;
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700122
Yuri Wiitalab929b832019-06-05 17:13:15 -0700123 // This mutex is used for |tasks_| and |delayed_tasks_|, and also for
124 // notifying the run loop to wake up when it is waiting for a task to be added
125 // to the queue in |run_loop_wakeup_|.
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700126 std::mutex task_mutex_;
Ryan Keaneefab2ed2019-07-22 12:36:53 -0700127 std::vector<TaskWithMetadata> tasks_ GUARDED_BY(task_mutex_);
128 std::multimap<Clock::time_point, TaskWithMetadata> delayed_tasks_
129 GUARDED_BY(task_mutex_);
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700130
btolschd94fe622019-05-09 14:21:40 -0700131 // When |task_waiter_| is nullptr, |run_loop_wakeup_| is used for sleeping the
132 // task runner. Otherwise, |run_loop_wakeup_| isn't used and |task_waiter_|
133 // is used instead (along with |waiter_timeout_|).
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700134 std::condition_variable run_loop_wakeup_;
btolschd94fe622019-05-09 14:21:40 -0700135 TaskWaiter* const task_waiter_;
136 Clock::duration waiter_timeout_;
Yuri Wiitalab929b832019-06-05 17:13:15 -0700137
138 // To prevent excessive re-allocation of the underlying array of the |tasks_|
139 // vector, use an A/B vector-swap mechanism. |running_tasks_| starts out
140 // empty, and is swapped with |tasks_| when it is time to run the Tasks.
Ryan Keaneefab2ed2019-07-22 12:36:53 -0700141 std::vector<TaskWithMetadata> running_tasks_;
Ryan Keane32c88d02019-07-02 18:46:14 -0700142
Max Yakimakhabf567dc2019-09-20 13:37:04 -0700143 std::thread::id task_runner_thread_id_;
144
Ryan Keane32c88d02019-07-02 18:46:14 -0700145 OSP_DISALLOW_COPY_AND_ASSIGN(TaskRunnerImpl);
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700146};
Jordan Baylesb0c191e2019-03-26 15:49:57 -0700147} // namespace openscreen
148
Jordan Baylesa26582d2019-07-10 14:44:58 -0700149#endif // PLATFORM_IMPL_TASK_RUNNER_H_