1 /*
2  * Copyright (c) 2022 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_queue.h"
17 #include "tools/log.h"
18 
19 namespace Commonlibrary::Concurrent::WorkerModule {
EnQueue(MessageDataType data)20 void MessageQueue::EnQueue(MessageDataType data)
21 {
22     queueLock_.lock();
23     queue_.push(data);
24     queueLock_.unlock();
25 }
26 
DeQueue(MessageDataType * data)27 bool MessageQueue::DeQueue(MessageDataType *data)
28 {
29     queueLock_.lock();
30     if (queue_.empty()) {
31         queueLock_.unlock();
32         return false;
33     }
34     if (data != nullptr) {
35         *data = queue_.front();
36         queue_.pop();
37     } else {
38         HILOG_ERROR("worker:: data is nullptr.");
39     }
40     queueLock_.unlock();
41     return true;
42 }
43 
IsEmpty() const44 bool MessageQueue::IsEmpty() const
45 {
46     return queue_.empty();
47 }
48 
Clear(napi_env env)49 void MessageQueue::Clear(napi_env env)
50 {
51     queueLock_.lock();
52     size_t size = queue_.size();
53     for (size_t i = 0; i < size; i++) {
54         MessageDataType data = queue_.front();
55         napi_delete_serialization_data(env, data);
56         queue_.pop();
57     }
58     queueLock_.unlock();
59 }
60 
Push(uint32_t id,MessageDataType data)61 void MarkedMessageQueue::Push(uint32_t id, MessageDataType data)
62 {
63     std::unique_lock<std::mutex> lock(queueLock_);
64     queue_.push({id, data});
65 }
66 
Pop()67 void MarkedMessageQueue::Pop()
68 {
69     std::unique_lock<std::mutex> lock(queueLock_);
70     queue_.pop();
71 }
72 
Front()73 std::pair<uint32_t, MessageDataType> MarkedMessageQueue::Front()
74 {
75     std::unique_lock<std::mutex> lock(queueLock_);
76     return queue_.front();
77 }
78 
IsEmpty()79 bool MarkedMessageQueue::IsEmpty()
80 {
81     std::unique_lock<std::mutex> lock(queueLock_);
82     return queue_.empty();
83 }
84 
Clear(napi_env env)85 void MarkedMessageQueue::Clear(napi_env env)
86 {
87     std::unique_lock<std::mutex> lock(queueLock_);
88     while (!queue_.empty()) {
89         std::pair<uint32_t, MessageDataType> pair = queue_.front();
90         napi_delete_serialization_data(env, pair.second);
91         queue_.pop();
92     }
93 }
94 }  // namespace Commonlibrary::Concurrent::WorkerModule
95