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