1 /* 2 * Copyright (c) 2021-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 #ifndef FOUNDATION_ACE_NAPI_NATIVE_ENGINE_NATIVE_ASYNC_WORK_H 17 #define FOUNDATION_ACE_NAPI_NATIVE_ENGINE_NATIVE_ASYNC_WORK_H 18 19 #include "native_value.h" 20 21 #include <mutex> 22 #include <queue> 23 #include <uv.h> 24 25 struct NativeAsyncWorkDataPointer { NativeAsyncWorkDataPointerNativeAsyncWorkDataPointer26 NativeAsyncWorkDataPointer() 27 { 28 data_ = nullptr; 29 } 30 NativeAsyncWorkDataPointerNativeAsyncWorkDataPointer31 explicit NativeAsyncWorkDataPointer(void* data) 32 { 33 data_ = data; 34 } 35 void* data_ { nullptr }; 36 }; 37 38 #ifdef ENABLE_HITRACE 39 namespace OHOS { 40 namespace HiviewDFX { 41 class HiTraceId; 42 } 43 } // namespace OHOS 44 #endif 45 46 class NativeAsyncWork { 47 public: 48 NativeAsyncWork(NativeEngine* engine, 49 NativeAsyncExecuteCallback execute, 50 NativeAsyncCompleteCallback complete, 51 void* data); 52 53 virtual ~NativeAsyncWork(); 54 virtual bool Queue(); 55 virtual bool Cancel(); 56 virtual bool Init(); 57 virtual void Send(void* data); 58 virtual void Close(); 59 virtual bool PopData(NativeAsyncWorkDataPointer* data); 60 61 template<typename Inner, typename Outer> DereferenceOf(const Inner Outer::* field,const Inner * pointer)62 static Outer* DereferenceOf(const Inner Outer::*field, const Inner* pointer) 63 { 64 if (field != nullptr && pointer != nullptr) { 65 auto fieldOffset = reinterpret_cast<uintptr_t>(&(static_cast<Outer*>(0)->*field)); 66 auto outPointer = reinterpret_cast<Outer*>(reinterpret_cast<uintptr_t>(pointer) - fieldOffset); 67 return outPointer; 68 } 69 return nullptr; 70 } 71 72 private: 73 static void AsyncWorkCallback(uv_work_t* req); 74 static void AsyncAfterWorkCallback(uv_work_t* req, int status); 75 static void AsyncWorkRecvCallback(const uv_async_t* req); 76 77 uv_work_t work_; 78 uv_async_t workAsyncHandler_; 79 NativeEngine* engine_; 80 NativeAsyncExecuteCallback execute_; 81 NativeAsyncCompleteCallback complete_; 82 void* data_; 83 std::mutex workAsyncMutex_; 84 std::queue<NativeAsyncWorkDataPointer> asyncWorkRecvData_; 85 #ifdef ENABLE_HITRACE 86 std::unique_ptr<OHOS::HiviewDFX::HiTraceId> traceId_; 87 #endif 88 #ifdef ENABLE_CONTAINER_SCOPE 89 int32_t containerScopeId_; 90 #endif 91 }; 92 93 #endif /* FOUNDATION_ACE_NAPI_NATIVE_ENGINE_NATIVE_ASYNC_WORK_H */ 94