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 16 #ifndef FOUNDATION_ACE_NAPI_NATIVE_ENGINE_NATIVE_SAFE_ASYNC_WORK_H 17 #define FOUNDATION_ACE_NAPI_NATIVE_ENGINE_NATIVE_SAFE_ASYNC_WORK_H 18 19 #include "native_value.h" 20 21 #include <mutex> 22 #include <queue> 23 #include <uv.h> 24 #ifdef LINUX_PLATFORM 25 #include <condition_variable> 26 #endif 27 28 #include "native_async_context.h" 29 30 enum class SafeAsyncCode { 31 UNKNOWN = 0, 32 SAFE_ASYNC_QUEUE_FULL, 33 SAFE_ASYNC_INVALID_ARGS, 34 SAFE_ASYNC_CLOSED, 35 SAFE_ASYNC_FAILED, 36 SAFE_ASYNC_OK, 37 }; 38 39 enum class SafeAsyncStatus { 40 UNKNOW = 0, 41 SAFE_ASYNC_STATUS_INTE, 42 SAFE_ASYNC_STATUS_CLOSING, 43 SAFE_ASYNC_STATUS_CLOSED, 44 }; 45 46 class NativeSafeAsyncWork { 47 public: 48 static void AsyncCallback(uv_async_t* asyncHandler); 49 static void IdleCallback(uv_idle_t* idleHandler); 50 static void CallJs(NativeEngine* engine, NativeValue* js_call_func, void* context, void* data); 51 52 NativeSafeAsyncWork(NativeEngine* engine, 53 NativeValue* func, 54 NativeValue* asyncResource, 55 NativeValue* asyncResourceName, 56 size_t maxQueueSize, 57 size_t threadCount, 58 void* finalizeData, 59 NativeFinalize finalizeCallback, 60 void* context, 61 NativeThreadSafeFunctionCallJs callJsCallback); 62 63 virtual ~NativeSafeAsyncWork(); 64 virtual bool Init(); 65 virtual SafeAsyncCode Send(void* data, NativeThreadSafeFunctionCallMode mode); 66 virtual SafeAsyncCode Acquire(); 67 virtual SafeAsyncCode Release(NativeThreadSafeFunctionReleaseMode mode); 68 virtual bool Ref(); 69 virtual bool Unref(); 70 virtual void* GetContext(); 71 72 private: 73 void ProcessAsyncHandle(); 74 SafeAsyncCode CloseHandles(); 75 void CleanUp(); 76 bool IsSameTid(); 77 bool IsMaxQueueSize(); 78 79 NativeEngine* engine_ = nullptr; 80 NativeReference* ref_ = nullptr; 81 size_t maxQueueSize_ = 0; 82 size_t threadCount_ = 0; 83 void* finalizeData_ = nullptr; 84 NativeFinalize finalizeCallback_ = nullptr; 85 void* context_ = nullptr; 86 NativeThreadSafeFunctionCallJs callJsCallback_ = nullptr; 87 NativeAsyncContext asyncContext_; 88 uv_async_t asyncHandler_; 89 uv_idle_t idleHandler_; 90 std::mutex mutex_; 91 std::queue<void*> queue_; 92 std::condition_variable condition_; 93 SafeAsyncStatus status_ = SafeAsyncStatus::UNKNOW; 94 }; 95 96 #endif /* FOUNDATION_ACE_NAPI_NATIVE_ENGINE_NATIVE_SAFE_ASYNC_WORK_H */ 97