blob: d9dea0ba13c77e8d7e447eb8362f0f14ecacdf3a [file] [log] [blame]
Hansong Zhanga25f84d2019-03-19 16:17:42 -07001/*
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
Hansong Zhangaa0875c2019-06-06 21:44:55 -070024#include "common/callback.h"
Hansong Zhanga25f84d2019-03-19 16:17:42 -070025#include "os/thread.h"
26#include "os/utils.h"
27
28namespace bluetooth {
29namespace 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.
34class 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
Hansong Zhangaa0875c2019-06-06 21:44:55 -070045 void Post(OnceClosure closure);
Hansong Zhanga25f84d2019-03-19 16:17:42 -070046
47 // Remove all pending events from the queue of this handler
48 void Clear();
49
Myles Watson742fe6d2019-06-07 08:57:16 -070050 // Die if the current reactable doesn't stop before the timeout. Must be called after Clear()
51 void WaitUntilStopped(std::chrono::milliseconds timeout);
52
Chienyuan87d813d2019-04-04 10:29:02 -070053 template <typename T>
54 friend class Queue;
55
Myles Watson2ba4b302019-06-03 09:25:28 -070056 friend class Alarm;
57
58 friend class RepeatingAlarm;
59
Hansong Zhanga25f84d2019-03-19 16:17:42 -070060 private:
Myles Watson742fe6d2019-06-07 08:57:16 -070061 inline bool was_cleared() const {
62 return tasks_ == nullptr;
63 };
Hansong Zhangaa0875c2019-06-06 21:44:55 -070064 std::queue<OnceClosure>* tasks_;
Myles Watsondde08cd2019-06-03 09:06:26 -070065 Thread* thread_;
Hansong Zhanga25f84d2019-03-19 16:17:42 -070066 int fd_;
67 Reactor::Reactable* reactable_;
68 mutable std::mutex mutex_;
69 void handle_next_event();
70};
71
72} // namespace os
73} // namespace bluetooth