• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
23 #include "os/thread.h"
24 #include "os/utils.h"
25 
26 namespace bluetooth {
27 namespace os {
28 
29 // A single-shot alarm for reactor-based thread, implemented by Linux timerfd.
30 // When it's constructed, it will register a reactable on the specified thread; when it's destroyed, it will unregister
31 // itself from the thread.
32 class Alarm {
33  public:
34   // Create and register a single-shot alarm on given thread
35   explicit Alarm(Thread* thread);
36 
37   // Unregister this alarm from the thread and release resource
38   ~Alarm();
39 
40   DISALLOW_COPY_AND_ASSIGN(Alarm);
41 
42   // Schedule the alarm with given delay
43   void Schedule(Closure task, std::chrono::milliseconds delay);
44 
45   // Cancel the alarm. No-op if it's not armed.
46   void Cancel();
47 
48  private:
49   Closure task_;
50   Thread* thread_;
51   int fd_ = 0;
52   Reactor::Reactable* token_;
53   mutable std::mutex mutex_;
54   void on_fire();
55 };
56 
57 }  // namespace os
58 
59 }  // namespace bluetooth
60