• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
16 #include "message_handler.h"
17 
18 namespace OHOS {
19 namespace MiscServices {
20     /*! Constructor
21     */
MessageHandler()22     MessageHandler::MessageHandler()
23     {
24     }
25 
26     /*! Destructor
27     */
~MessageHandler()28     MessageHandler::~MessageHandler()
29     {
30         std::unique_lock<std::mutex> lock(mMutex);
31         while (! mQueue.empty()) {
32             Message *msg = mQueue.front();
33             mQueue.pop();
34             delete msg;
35             msg = nullptr;
36         }
37     }
38 
39     /*! Send a message
40       \param msg a message to be sent
41       \note the msg pointer should not be freed by the caller
42     */
SendMessage(Message * msg)43     void MessageHandler::SendMessage(Message *msg)
44     {
45         {
46             std::unique_lock<std::mutex> lock(mMutex);
47             mQueue.push(msg);
48         }
49         mCV.notify_one();
50     }
51 
52     /*! Get a message
53       \return a pointer referred to an object of message
54       \note the returned pointer should be freed by the caller.
55     */
GetMessage()56     Message *MessageHandler::GetMessage()
57     {
58         std::unique_lock<std::mutex> lock(mMutex);
59         mCV.wait(lock, [this] {
60             return !this->mQueue.empty();
61         });
62 
63         Message *msg = (Message*) mQueue.front();
64         mQueue.pop();
65         return msg;
66     }
67 
68     /*! The single instance of MessageHandler in the service
69       \return the pointer referred to an object.
70     */
Instance()71     MessageHandler *MessageHandler::Instance()
72     {
73         static MessageHandler *handler = nullptr;
74         if (handler == nullptr) {
75             handler = new MessageHandler();
76         }
77         return handler;
78     }
79 }
80 }
81 
82