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 #ifndef AVPLAY_MESSAGE_LOOPER_H 17 #define AVPLAY_MESSAGE_LOOPER_H 18 #include <pthread.h> 19 #include <list> 20 #include <string> 21 #include "message_handler.h" 22 #include "fsm_message.h" 23 #include "mmessage_pool.h" 24 25 namespace OHOS { 26 struct MsgEvent { 27 MsgInfo *msg; 28 uint64_t whenUs; 29 }; 30 31 class MessageLooper { 32 public: 33 explicit MessageLooper(std::string name); 34 int32_t Init(uint32_t maxQueueSize, uint32_t msgPayloadLen, std::string name); 35 int32_t Deinit(); 36 virtual ~MessageLooper(); 37 int32_t RegisterHandler(MessageHandler &handler); 38 int32_t Start(); 39 int32_t Stop(); 40 int32_t Send(const MsgInfo &msg); 41 int32_t Post(const MsgInfo &msg, uint64_t delayUs); 42 bool HasMessage(const MsgInfo &msg); 43 void RemoveMessage(const MsgInfo &msg); 44 void Dump(); 45 MessageLooper(const MessageLooper &) = delete; 46 MessageLooper &operator=(const MessageLooper &) = delete; 47 48 private: 49 static void *Looper(void *args); 50 void QueueHandlr(); 51 void InsertQueue(MsgInfo &msg, uint64_t delayUs); 52 void LockHandler(); 53 void UnlockHandler(); 54 55 private: 56 MessageHandler *m_msgHandlr = nullptr; 57 bool m_isThreadRunning = false; 58 std::list<MsgEvent> m_eventQueue; 59 pthread_cond_t m_queueCondition = PTHREAD_COND_INITIALIZER; 60 pthread_mutex_t m_queueLock = PTHREAD_MUTEX_INITIALIZER; 61 pthread_t m_loopThrd = 0; 62 std::string m_name; 63 pthread_mutex_t m_handlerMutex = PTHREAD_MUTEX_INITIALIZER; 64 bool m_isInited = false; 65 MMessagePool *m_msgPool = nullptr; 66 }; 67 }; 68 #endif // AVPLAY_MESSAGE_LOOPER_H 69