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 <memory> 20 #include <mutex> 21 #include <queue> 22 23 #include "common/bind.h" 24 #include "common/callback.h" 25 #include "common/postable_context.h" 26 #include "os/thread.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 : public common::PostableContext { 35 public: 36 // Create and register a handler on given thread 37 explicit Handler(Thread* thread); 38 39 Handler(const Handler&) = delete; 40 Handler& operator=(const Handler&) = delete; 41 42 // Unregister this handler from the thread and release resource. Unhandled events will be discarded and not executed. 43 virtual ~Handler(); 44 45 // Enqueue a closure to the queue of this handler 46 virtual void Post(common::OnceClosure closure) override; 47 48 // Remove all pending events from the queue of this handler 49 void Clear(); 50 51 // Die if the current reactable doesn't stop before the timeout. Must be called after Clear() 52 void WaitUntilStopped(std::chrono::milliseconds timeout); 53 54 template <typename Functor, typename... Args> Call(Functor && functor,Args &&...args)55 void Call(Functor&& functor, Args&&... args) { 56 Post(common::BindOnce(std::forward<Functor>(functor), std::forward<Args>(args)...)); 57 } 58 59 template <typename T, typename Functor, typename... Args> CallOn(T * obj,Functor && functor,Args &&...args)60 void CallOn(T* obj, Functor&& functor, Args&&... args) { 61 Post(common::BindOnce(std::forward<Functor>(functor), common::Unretained(obj), std::forward<Args>(args)...)); 62 } 63 64 template <typename T> 65 friend class Queue; 66 67 friend class Alarm; 68 69 friend class RepeatingAlarm; 70 71 private: was_cleared()72 inline bool was_cleared() const { 73 return tasks_ == nullptr; 74 }; 75 std::queue<common::OnceClosure>* tasks_; 76 Thread* thread_; 77 std::unique_ptr<Reactor::Event> event_; 78 Reactor::Reactable* reactable_; 79 mutable std::mutex mutex_; 80 void handle_next_event(); 81 }; 82 83 } // namespace os 84 } // namespace bluetooth 85