1 // Copyright 2021 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 #pragma once 15 16 #include <memory> 17 #include <mutex> 18 19 #include "pw_chrono/system_clock.h" 20 #include "pw_function/function.h" 21 22 namespace pw::chrono::backend { 23 24 struct NativeSystemTimer { 25 // Instead of using a more complex blocking timer cleanup, a shared_pointer is 26 // used so that the heap allocation is still valid for the detached threads 27 // even after the NativeSystemTimer has been destructed. Note this is shared 28 // with all detached threads. 29 struct CallbackContext { CallbackContextNativeSystemTimer::CallbackContext30 CallbackContext( 31 Function<void(SystemClock::time_point expired_deadline)>&& cb) 32 : callback(std::move(cb)) {} 33 34 const Function<void(SystemClock::time_point expired_deadline)> callback; 35 36 // The mutex is used both to ensure the public API is threadsafe and to 37 // ensure that only one expiry callback is executed at time. 38 // A recurisve mutex is used as the timer callback must be able to invoke 39 // its own public API. 40 std::recursive_mutex mutex; 41 }; 42 std::shared_ptr<CallbackContext> callback_context; 43 44 // This is only shared with the last active timer if there is one. Note that 45 // this is guarded by the callback_context's mutex. 46 std::shared_ptr<bool> active_timer_enabled; 47 }; 48 49 using NativeSystemTimerHandle = NativeSystemTimer&; 50 51 } // namespace pw::chrono::backend 52