• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #include "pw_async_basic/dispatcher.h"
15 
16 #include "pw_assert/check.h"
17 #include "pw_chrono/system_clock.h"
18 #include "pw_log/log.h"
19 
20 using namespace std::chrono_literals;
21 
22 namespace pw::async {
23 
24 const chrono::SystemClock::duration SLEEP_DURATION = 5s;
25 
~BasicDispatcher()26 BasicDispatcher::~BasicDispatcher() {
27   RequestStop();
28   lock_.lock();
29   DrainTaskQueue();
30   lock_.unlock();
31 }
32 
Run()33 void BasicDispatcher::Run() {
34   lock_.lock();
35   while (!stop_requested_) {
36     MaybeSleep();
37     ExecuteDueTasks();
38   }
39   DrainTaskQueue();
40   lock_.unlock();
41 }
42 
RunUntilIdle()43 void BasicDispatcher::RunUntilIdle() {
44   lock_.lock();
45   ExecuteDueTasks();
46   if (stop_requested_) {
47     DrainTaskQueue();
48   }
49   lock_.unlock();
50 }
51 
RunUntil(chrono::SystemClock::time_point end_time)52 void BasicDispatcher::RunUntil(chrono::SystemClock::time_point end_time) {
53   lock_.lock();
54   while (end_time < now() && !stop_requested_) {
55     MaybeSleep();
56     ExecuteDueTasks();
57   }
58   if (stop_requested_) {
59     DrainTaskQueue();
60   }
61   lock_.unlock();
62 }
63 
RunFor(chrono::SystemClock::duration duration)64 void BasicDispatcher::RunFor(chrono::SystemClock::duration duration) {
65   RunUntil(now() + duration);
66 }
67 
MaybeSleep()68 void BasicDispatcher::MaybeSleep() {
69   if (task_queue_.empty() || task_queue_.front().due_time_ > now()) {
70     // Sleep until a notification is received or until the due time of the
71     // next task. Notifications are sent when tasks are posted or 'stop' is
72     // requested.
73     chrono::SystemClock::time_point wake_time =
74         task_queue_.empty() ? now() + SLEEP_DURATION
75                             : task_queue_.front().due_time_;
76 
77     lock_.unlock();
78     PW_LOG_DEBUG("no task due; waiting for signal");
79     timed_notification_.try_acquire_until(wake_time);
80     lock_.lock();
81   }
82 }
83 
ExecuteDueTasks()84 void BasicDispatcher::ExecuteDueTasks() {
85   while (!task_queue_.empty() && task_queue_.front().due_time_ <= now() &&
86          !stop_requested_) {
87     backend::NativeTask& task = task_queue_.front();
88     task_queue_.pop_front();
89 
90     if (task.interval().has_value()) {
91       PostTaskInternal(task, task.due_time_ + task.interval().value());
92     }
93 
94     lock_.unlock();
95     PW_LOG_DEBUG("running task");
96     Context ctx{this, &task.task_};
97     task(ctx, OkStatus());
98     lock_.lock();
99   }
100 }
101 
RequestStop()102 void BasicDispatcher::RequestStop() {
103   std::lock_guard lock(lock_);
104   PW_LOG_DEBUG("stop requested");
105   stop_requested_ = true;
106   timed_notification_.release();
107 }
108 
DrainTaskQueue()109 void BasicDispatcher::DrainTaskQueue() {
110   PW_LOG_DEBUG("draining task queue");
111   while (!task_queue_.empty()) {
112     backend::NativeTask& task = task_queue_.front();
113     task_queue_.pop_front();
114 
115     lock_.unlock();
116     PW_LOG_DEBUG("running cancelled task");
117     Context ctx{this, &task.task_};
118     task(ctx, Status::Cancelled());
119     lock_.lock();
120   }
121 }
122 
Post(Task & task)123 void BasicDispatcher::Post(Task& task) { PostAt(task, now()); }
124 
PostAfter(Task & task,chrono::SystemClock::duration delay)125 void BasicDispatcher::PostAfter(Task& task,
126                                 chrono::SystemClock::duration delay) {
127   PostAt(task, now() + delay);
128 }
129 
PostAt(Task & task,chrono::SystemClock::time_point time)130 void BasicDispatcher::PostAt(Task& task, chrono::SystemClock::time_point time) {
131   lock_.lock();
132   PW_LOG_DEBUG("posting task");
133   PostTaskInternal(task.native_type(), time);
134   lock_.unlock();
135 }
136 
PostPeriodic(Task & task,chrono::SystemClock::duration interval)137 void BasicDispatcher::PostPeriodic(Task& task,
138                                    chrono::SystemClock::duration interval) {
139   PostPeriodicAt(task, interval, now());
140 }
141 
PostPeriodicAt(Task & task,chrono::SystemClock::duration interval,chrono::SystemClock::time_point start_time)142 void BasicDispatcher::PostPeriodicAt(
143     Task& task,
144     chrono::SystemClock::duration interval,
145     chrono::SystemClock::time_point start_time) {
146   PW_DCHECK(interval != chrono::SystemClock::duration::zero());
147   task.native_type().set_interval(interval);
148   PostAt(task, start_time);
149 }
150 
Cancel(Task & task)151 bool BasicDispatcher::Cancel(Task& task) {
152   std::lock_guard lock(lock_);
153   return task_queue_.remove(task.native_type());
154 }
155 
PostTaskInternal(backend::NativeTask & task,chrono::SystemClock::time_point time_due)156 void BasicDispatcher::PostTaskInternal(
157     backend::NativeTask& task, chrono::SystemClock::time_point time_due) {
158   task.due_time_ = time_due;
159   auto it_front = task_queue_.begin();
160   auto it_behind = task_queue_.before_begin();
161   while (it_front != task_queue_.end() && time_due > it_front->due_time_) {
162     ++it_front;
163     ++it_behind;
164   }
165   task_queue_.insert_after(it_behind, task);
166   timed_notification_.release();
167 }
168 
169 }  // namespace pw::async
170