1 /* 2 * Copyright (c) 2020-2021 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 #include "event_handler.h" 17 18 using namespace std; 19 20 namespace OHOS { 21 namespace Media { EventHandler()22EventHandler::EventHandler() : running_(false) 23 { 24 hdlThrd_ = new thread(EventDispatch, this); 25 } 26 ~EventHandler()27EventHandler::~EventHandler() 28 { 29 while (!running_) { 30 this_thread::yield(); 31 } 32 running_ = false; 33 cv_.notify_all(); 34 hdlThrd_->join(); 35 delete hdlThrd_; 36 } 37 IsRunning()38bool EventHandler::IsRunning() 39 { 40 return running_; 41 } 42 EventDispatch(EventHandler * hdl)43void EventHandler::EventDispatch(EventHandler *hdl) 44 { 45 if (hdl == nullptr) { 46 return; 47 } 48 std::unique_lock<std::mutex> lock(hdl->mtx_); 49 hdl->running_ = true; 50 while (hdl->running_) { 51 if (hdl->msgQ_.empty()) { 52 hdl->cv_.wait(lock); // wait for task or exit signal 53 } else { 54 auto mission = hdl->msgQ_.front(); 55 hdl->msgQ_.pop(); 56 lock.unlock(); 57 mission->Exec(); 58 delete mission; 59 lock.lock(); 60 } 61 } 62 /* Exec all tasks before exit */ 63 while (!hdl->msgQ_.empty()) { 64 auto mission = hdl->msgQ_.front(); 65 hdl->msgQ_.pop(); 66 lock.unlock(); 67 mission->Exec(); 68 delete mission; 69 lock.lock(); 70 } 71 } 72 } // namespace Media 73 } // namespace OHOS