1/* 2 * Copyright (c) 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#include "event.h" 16#include <cstdio> 17#include <iostream> 18 19namespace STtools { 20int WaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout) 21{ 22 return event.WaitingMessage(std::to_string(code) + eventName, timeout, false); 23} 24 25void Completed(Event &event, const std::string &eventName, const int code) 26{ 27 return event.CompleteMessage(std::to_string(code) + eventName); 28} 29 30void CleanMsg(Event &event) 31{ 32 return event.Clean(); 33} 34 35Event::Event() 36{ 37 waiting_message_ = ""; 38 complete_message_.clear(); 39} 40 41Event::~Event() 42{ 43 waiting_message_ = ""; 44 std::vector<std::string> tmp_vector; 45 tmp_vector.swap(complete_message_); 46 complete_message_.clear(); 47} 48 49bool Event::Compare() 50{ 51 if (!waiting_message_.empty()) { 52 for (size_t i = 0; i < complete_message_.size(); i++) { 53 if (waiting_message_.compare(complete_message_.at(i)) == 0) { 54 complete_message_.erase(std::begin(complete_message_) + i, std::begin(complete_message_) + i + 1); 55 waiting_message_ = ""; 56 return true; 57 } 58 } 59 } 60 return false; 61} 62 63int Event::WaitingMessage(const std::string &message, int timeout_ms, bool locked) 64{ 65 std::unique_lock<std::mutex> lock(mutex_); 66 waiting_message_ = message; 67 if (Compare()) { 68 return 0; 69 } 70 71 if (locked) { 72 cv_.wait(lock); 73 return 0; 74 } 75 76 if (cv_.wait_for(lock, std::chrono::seconds(timeout_ms)) == std::cv_status::timeout) { 77 waiting_message_ = ""; 78 return -1; 79 } 80 return 0; 81} 82 83void Event::CompleteMessage(const std::string &message) 84{ 85 std::unique_lock<std::mutex> lock(mutex_); 86 if (waiting_message_.compare(message) == 0) { 87 waiting_message_ = ""; 88 cv_.notify_all(); 89 return; 90 } 91 complete_message_.push_back(message); 92 return; 93} 94 95void Event::Clean() 96{ 97 waiting_message_ = ""; 98 complete_message_.clear(); 99} 100} // namespace STtools