• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2024 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 <atomic>
16 
17 #include "gtest/gtest.h"
18 #include "pw_async2/dispatcher.h"
19 #include "pw_function/function.h"
20 #include "pw_thread/sleep.h"
21 #include "pw_thread/thread.h"
22 #include "pw_thread_stl/options.h"
23 
24 namespace pw::async2 {
25 namespace {
26 
27 using namespace std::chrono_literals;
28 
29 class MockTask : public Task {
30  public:
31   std::atomic_bool should_complete = false;
32   std::atomic_int polled = 0;
33   std::atomic_int destroyed = 0;
34   Waker last_waker;
35 
36  private:
DoPend(Context & cx)37   Poll<> DoPend(Context& cx) override {
38     ++polled;
39     PW_ASYNC_STORE_WAKER(cx, last_waker, "MockTask is waiting for last_waker");
40     if (should_complete) {
41       return Ready();
42     } else {
43       return Pending();
44     }
45   }
DoDestroy()46   void DoDestroy() override { ++destroyed; }
47 };
48 
TEST(Dispatcher,RunToCompletion_SleepsUntilWoken)49 TEST(Dispatcher, RunToCompletion_SleepsUntilWoken) {
50   MockTask task;
51   task.should_complete = false;
52   Dispatcher dispatcher;
53   dispatcher.Post(task);
54 
55   Thread work_thread(thread::stl::Options(), [&task]() {
56     this_thread::sleep_for(100ms);
57     task.should_complete = true;
58     std::move(task.last_waker).Wake();
59   });
60 
61   dispatcher.RunToCompletion(task);
62 
63   work_thread.join();
64 
65   // Poll once when sleeping then once when woken.
66   EXPECT_EQ(task.polled, 2);
67   EXPECT_EQ(task.destroyed, 1);
68 }
69 
70 }  // namespace
71 }  // namespace pw::async2
72