1 /* 2 * Copyright (C) 2021-2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef DISPATCHER_H 17 #define DISPATCHER_H 18 19 #include <atomic> 20 #include <functional> 21 #include <future> 22 #include <memory> 23 #include <string> 24 #include <thread> 25 #include "fixed_queue.h" 26 27 namespace utility { 28 class Dispatcher { 29 public: 30 /** 31 * @brief Construct a new Dispatcher object. 32 * 33 * @param name Dispatcher name. 34 * @since 6 35 */ 36 explicit Dispatcher(const std::string &name = "bt-dispatcher"); 37 38 /** 39 * @brief Destroy the Dispatcher object 40 * 41 * @since 6 42 */ 43 virtual ~Dispatcher(); 44 45 /** 46 * @brief Initialize the Dispatcher object 47 * 48 * @since 6 49 */ 50 void Initialize(); 51 52 /** 53 * @brief Uninitialize the Dispatcher object 54 * 55 * @since 6 56 */ 57 void Uninitialize(); 58 59 /** 60 * @brief PostTask to dispatcher. 61 * 62 * @param task 63 * @since 6 64 */ 65 void PostTask(const std::function<void()> &task); 66 67 /** 68 * @brief Get Dispatcher name. 69 * 70 * @return Dispatcher's name. 71 * @since 6 72 */ 73 const std::string &Name() const; 74 75 private: 76 /** 77 * @brief Run Dispatcher function. 78 * 79 * @param dispatcher Dispatcher pointer. 80 * @since 6 81 */ 82 void Run(std::promise<void> promise); 83 84 std::string name_ {""}; 85 std::mutex mutex_ {}; 86 std::unique_ptr<std::thread> thread_ {nullptr}; 87 std::atomic_bool start_ = ATOMIC_FLAG_INIT; 88 utility::FixedQueue<std::function<void()>> taskQueue_ {}; 89 90 BT_DISALLOW_COPY_AND_ASSIGN(Dispatcher); 91 }; 92 } // namespace utility 93 94 #endif // DISPATCHER_H