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