blob: dc6d51034490a93b92a9a5d05289c71a327c2280 [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
24#include "os/thread.h"
25#include "os/utils.h"
26
27namespace bluetooth {
28namespace os {
29
30// A message-queue style handler for reactor-based thread to handle incoming events from different threads. When it's
31// constructed, it will register a reactable on the specified thread; when it's destroyed, it will unregister itself
32// from the thread.
33class Handler {
34 public:
35 // Create and register a handler on given thread
36 explicit Handler(Thread* thread);
37
38 // Unregister this handler from the thread and release resource. Unhandled events will be discarded and not executed.
39 ~Handler();
40
41 DISALLOW_COPY_AND_ASSIGN(Handler);
42
43 // Enqueue a closure to the queue of this handler
44 void Post(Closure closure);
45
46 // Remove all pending events from the queue of this handler
47 void Clear();
48
49 private:
50 std::queue<Closure> tasks_;
51 Thread* thread_;
52 int fd_;
53 Reactor::Reactable* reactable_;
54 mutable std::mutex mutex_;
55 void handle_next_event();
56};
57
58} // namespace os
59} // namespace bluetooth