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