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