1 /*
2  * Copyright (c) 2023-2024 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 "uv_task_wrapper_impl.h"
17 
18 namespace OHOS::Ace::NG {
19 
UVTaskWrapperImpl(napi_env env)20 UVTaskWrapperImpl::UVTaskWrapperImpl(napi_env env)
21 {
22     if (env == nullptr) {
23         LOGE("env is null");
24         return;
25     }
26     auto engine = reinterpret_cast<NativeEngine*>(env);
27     if (engine == nullptr) {
28         LOGE("native engine is null");
29         return;
30     }
31     loop_ = engine->GetUVLoop();
32     threadId_ = engine->GetTid();
33 }
34 
WillRunOnCurrentThread()35 bool UVTaskWrapperImpl::WillRunOnCurrentThread()
36 {
37     return pthread_self() == threadId_;
38 }
39 
Call(const TaskExecutor::Task & task)40 void UVTaskWrapperImpl::Call(const TaskExecutor::Task& task)
41 {
42     if (loop_ == nullptr) {
43         LOGW("loop is null");
44         return;
45     }
46     UVWorkWrapper* workWrapper = new UVWorkWrapper(task);
47     uv_queue_work(
48         loop_, workWrapper, [](uv_work_t* req) {},
49         [](uv_work_t* req, int status) {
50             auto workWrapper = static_cast<UVWorkWrapper*>(req);
51             (*workWrapper)();
52             delete workWrapper;
53         });
54 }
55 } // namespace OHOS::Ace::NG
56