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