Hansong Zhang | a25f84d | 2019-03-19 16:17:42 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2019 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #pragma once |
| 18 | |
| 19 | #include <functional> |
| 20 | #include <memory> |
| 21 | #include <mutex> |
| 22 | |
Hansong Zhang | aa0875c | 2019-06-06 21:44:55 -0700 | [diff] [blame] | 23 | #include "common/callback.h" |
Myles Watson | 2ba4b30 | 2019-06-03 09:25:28 -0700 | [diff] [blame] | 24 | #include "os/handler.h" |
Hansong Zhang | a25f84d | 2019-03-19 16:17:42 -0700 | [diff] [blame] | 25 | #include "os/thread.h" |
| 26 | #include "os/utils.h" |
| 27 | |
| 28 | namespace bluetooth { |
| 29 | namespace os { |
| 30 | |
| 31 | // A single-shot alarm for reactor-based thread, implemented by Linux timerfd. |
| 32 | // When it's constructed, it will register a reactable on the specified thread; when it's destroyed, it will unregister |
| 33 | // itself from the thread. |
| 34 | class Alarm { |
| 35 | public: |
Myles Watson | 2ba4b30 | 2019-06-03 09:25:28 -0700 | [diff] [blame] | 36 | // Create and register a single-shot alarm on a given handler |
| 37 | explicit Alarm(Handler* handler); |
Hansong Zhang | a25f84d | 2019-03-19 16:17:42 -0700 | [diff] [blame] | 38 | |
| 39 | // Unregister this alarm from the thread and release resource |
| 40 | ~Alarm(); |
| 41 | |
| 42 | DISALLOW_COPY_AND_ASSIGN(Alarm); |
| 43 | |
| 44 | // Schedule the alarm with given delay |
Hansong Zhang | aa0875c | 2019-06-06 21:44:55 -0700 | [diff] [blame] | 45 | void Schedule(OnceClosure task, std::chrono::milliseconds delay); |
Hansong Zhang | a25f84d | 2019-03-19 16:17:42 -0700 | [diff] [blame] | 46 | |
| 47 | // Cancel the alarm. No-op if it's not armed. |
| 48 | void Cancel(); |
| 49 | |
| 50 | private: |
Hansong Zhang | aa0875c | 2019-06-06 21:44:55 -0700 | [diff] [blame] | 51 | OnceClosure task_; |
Myles Watson | 2ba4b30 | 2019-06-03 09:25:28 -0700 | [diff] [blame] | 52 | Handler* handler_; |
Hansong Zhang | a25f84d | 2019-03-19 16:17:42 -0700 | [diff] [blame] | 53 | int fd_ = 0; |
| 54 | Reactor::Reactable* token_; |
| 55 | mutable std::mutex mutex_; |
| 56 | void on_fire(); |
| 57 | }; |
| 58 | |
| 59 | } // namespace os |
| 60 | |
| 61 | } // namespace bluetooth |