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 #include "uv_queue.h"
16 #include "logger.h"
17
18 namespace OHOS::ObjectStore {
UvQueue(napi_env env)19 UvQueue::UvQueue(napi_env env) : env_(env)
20 {
21 napi_get_uv_event_loop(env, &loop_);
22 }
23
~UvQueue()24 UvQueue::~UvQueue()
25 {
26 LOG_DEBUG("no memory leak for queue-callback");
27 }
28
ExecUvWork(UvEntry * entry)29 void UvQueue::ExecUvWork(UvEntry *entry)
30 {
31 if (entry == nullptr) {
32 LOG_ERROR("entry is nullptr");
33 return;
34 }
35 auto queue = entry->uvQueue_.lock();
36 if (queue != nullptr) {
37 std::unique_lock<std::shared_mutex> cacheLock(queue->mutex_);
38 for (auto &item : queue->args_) {
39 item.first(queue->env_, item.second);
40 }
41 queue->args_.clear();
42 }
43 delete entry;
44 entry = nullptr;
45 }
46
CallFunction(Process process,void * argv)47 void UvQueue::CallFunction(Process process, void *argv)
48 {
49 if (process == nullptr || argv == nullptr) {
50 LOG_ERROR("nullptr");
51 return;
52 }
53 auto *uvEntry = new (std::nothrow)UvEntry { weak_from_this() };
54 if (uvEntry == nullptr) {
55 LOG_ERROR("no memory for UvEntry");
56 return;
57 }
58 {
59 std::unique_lock<std::shared_mutex> cacheLock(mutex_);
60 if (args_.count(process) != 0) {
61 std::list<void *> newData = args_.at(process);
62 newData.push_back(argv);
63 args_.insert_or_assign(process, newData);
64 } else {
65 std::list<void *> data;
66 data.push_back(argv);
67 args_.insert_or_assign(process, data);
68 }
69 }
70
71 auto task = [uvEntry]() {
72 UvQueue::ExecUvWork(uvEntry);
73 };
74 if (napi_send_event(env_, task, napi_eprio_high) != 0) {
75 if (uvEntry != nullptr) {
76 delete uvEntry;
77 uvEntry = nullptr;
78 }
79 }
80 }
81 } // namespace OHOS::ObjectStore
82