1 /* 2 * Copyright (C) 2023 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 * Description: API of message queue thread 16 */ 17 18 #ifndef MSGQUEUETHREAD_H 19 #define MSGQUEUETHREAD_H 20 21 #include <thread> 22 #include <mutex> 23 #include <condition_variable> 24 #include <functional> 25 #include <map> 26 #include <list> 27 #include "param_bundle.h" 28 29 using MsgType = int32_t; 30 using MsgId = uint64_t; 31 struct MsgInfo { 32 MsgType type; 33 MsgId id; 34 ParamSP param; 35 }; 36 37 class MsgHandleLoop { 38 protected: 39 MsgHandleLoop(); 40 ~MsgHandleLoop(); 41 void SendAsyncMsg(MsgType type, const ParamSP &msg, uint32_t delayUs = 0); 42 bool SendSyncMsg(MsgType type, const ParamSP &msg, ParamSP &reply, uint32_t waitMs = 0); 43 virtual void OnMsgReceived(const MsgInfo &info) = 0; 44 void PostReply(MsgId id, const ParamSP &reply); 45 void Stop(); 46 static constexpr MsgId ASYNC_MSG_ID = 0; 47 using TimeUs = int64_t; 48 static TimeUs GetNowUs(); 49 50 private: 51 void MainLoop(); 52 MsgId GenerateMsgId(); 53 54 private: 55 std::thread m_thread; 56 std::mutex m_mtx; 57 bool m_threadNeedStop = false; 58 MsgId m_lastMsgId = 0; 59 std::map<TimeUs, MsgInfo> m_msgQueue; // msg will be sorted by timeUs 60 std::condition_variable m_threadCond; 61 62 std::mutex m_replyMtx; 63 std::map<MsgId, ParamSP> m_replies; 64 std::condition_variable m_replyCond; 65 }; 66 67 68 #endif 69