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 #include <queue>
23 
24 #include "common/callback.h"
25 #include "os/thread.h"
26 #include "os/utils.h"
27 
28 namespace bluetooth {
29 namespace os {
30 
31 // A message-queue style handler for reactor-based thread to handle incoming events from different threads. When it's
32 // constructed, it will register a reactable on the specified thread; when it's destroyed, it will unregister itself
33 // from the thread.
34 class Handler {
35  public:
36   // Create and register a handler on given thread
37   explicit Handler(Thread* thread);
38 
39   // Unregister this handler from the thread and release resource. Unhandled events will be discarded and not executed.
40   ~Handler();
41 
42   DISALLOW_COPY_AND_ASSIGN(Handler);
43 
44   // Enqueue a closure to the queue of this handler
45   void Post(OnceClosure closure);
46 
47   // Remove all pending events from the queue of this handler
48   void Clear();
49 
50   // Die if the current reactable doesn't stop before the timeout.  Must be called after Clear()
51   void WaitUntilStopped(std::chrono::milliseconds timeout);
52 
53   template <typename T>
54   friend class Queue;
55 
56   friend class Alarm;
57 
58   friend class RepeatingAlarm;
59 
60  private:
61   inline bool was_cleared() const {
62     return tasks_ == nullptr;
63   };
64   std::queue<OnceClosure>* tasks_;
65   Thread* thread_;
66   int fd_;
67   Reactor::Reactable* reactable_;
68   mutable std::mutex mutex_;
69   void handle_next_event();
70 };
71 
72 }  // namespace os
73 }  // namespace bluetooth
74