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 #include "os/handler.h"
18
19 #include <bluetooth/log.h>
20
21 #include "common/bind.h"
22 #include "common/callback.h"
23 #include "os/log.h"
24 #include "os/reactor.h"
25
26 namespace bluetooth {
27 namespace os {
28 using common::OnceClosure;
29
Handler(Thread * thread)30 Handler::Handler(Thread* thread) : tasks_(new std::queue<OnceClosure>()), thread_(thread) {
31 event_ = thread_->GetReactor()->NewEvent();
32 reactable_ = thread_->GetReactor()->Register(
33 event_->Id(), common::Bind(&Handler::handle_next_event, common::Unretained(this)), common::Closure());
34 }
35
~Handler()36 Handler::~Handler() {
37 {
38 std::lock_guard<std::mutex> lock(mutex_);
39 log::assert_that(was_cleared(), "Handlers must be cleared before they are destroyed");
40 }
41 event_->Close();
42 }
43
Post(OnceClosure closure)44 void Handler::Post(OnceClosure closure) {
45 {
46 std::lock_guard<std::mutex> lock(mutex_);
47 if (was_cleared()) {
48 log::warn("Posting to a handler which has been cleared");
49 return;
50 }
51 tasks_->emplace(std::move(closure));
52 }
53 event_->Notify();
54 }
55
Clear()56 void Handler::Clear() {
57 std::queue<OnceClosure>* tmp = nullptr;
58 {
59 std::lock_guard<std::mutex> lock(mutex_);
60 log::assert_that(!was_cleared(), "Handlers must only be cleared once");
61 std::swap(tasks_, tmp);
62 }
63 delete tmp;
64
65 event_->Clear();
66
67 thread_->GetReactor()->Unregister(reactable_);
68 reactable_ = nullptr;
69 }
70
WaitUntilStopped(std::chrono::milliseconds timeout)71 void Handler::WaitUntilStopped(std::chrono::milliseconds timeout) {
72 log::assert_that(reactable_ == nullptr, "assert failed: reactable_ == nullptr");
73 log::assert_that(
74 thread_->GetReactor()->WaitForUnregisteredReactable(timeout),
75 "assert failed: thread_->GetReactor()->WaitForUnregisteredReactable(timeout)");
76 }
77
handle_next_event()78 void Handler::handle_next_event() {
79 common::OnceClosure closure;
80 {
81 std::lock_guard<std::mutex> lock(mutex_);
82 bool has_data = event_->Read();
83
84 if (was_cleared()) {
85 return;
86 }
87 log::assert_that(has_data, "Notified for work but no work available");
88
89 closure = std::move(tasks_->front());
90 tasks_->pop();
91 }
92 std::move(closure).Run();
93 }
94
95 } // namespace os
96 } // namespace bluetooth
97