• 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 
15 #include <mutex>
16 #include <optional>
17 
18 #include "pw_assert/check.h"
19 #include "pw_async2/dispatcher_native.h"
20 #include "pw_chrono/system_clock.h"
21 
22 namespace pw::async2 {
23 
DoRunUntilStalled(Task * task)24 Poll<> Dispatcher::DoRunUntilStalled(Task* task) {
25   {
26     std::lock_guard lock(dispatcher_lock());
27     PW_CHECK(task == nullptr || HasPostedTask(*task),
28              "Attempted to run a dispatcher until a task was stalled, "
29              "but that task has not been `Post`ed to that `Dispatcher`.");
30   }
31   while (true) {
32     RunOneTaskResult result = RunOneTask(task);
33     if (result.completed_main_task() || result.completed_all_tasks()) {
34       return Ready();
35     }
36     if (!result.ran_a_task()) {
37       return Pending();
38     }
39   }
40 }
41 
DoRunToCompletion(Task * task)42 void Dispatcher::DoRunToCompletion(Task* task) {
43   {
44     std::lock_guard lock(dispatcher_lock());
45     PW_CHECK(task == nullptr || HasPostedTask(*task),
46              "Attempted to run a dispatcher until a task was complete, "
47              "but that task has not been `Post`ed to that `Dispatcher`.");
48   }
49   while (true) {
50     RunOneTaskResult result = RunOneTask(task);
51     if (result.completed_main_task() || result.completed_all_tasks()) {
52       return;
53     }
54     if (!result.ran_a_task()) {
55       SleepInfo sleep_info = AttemptRequestWake();
56       if (sleep_info.should_sleep()) {
57         notify_.acquire();
58       }
59     }
60   }
61 }
62 
63 }  // namespace pw::async2
64