1 /*
2  * Copyright (c) 2023 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 JS_CONCURRENT_MODULE_TASKPOOL_TASK_GROUP_H
17 #define JS_CONCURRENT_MODULE_TASKPOOL_TASK_GROUP_H
18 
19 #include <list>
20 
21 #include "task.h"
22 #include "task_manager.h"
23 
24 namespace Commonlibrary::Concurrent::TaskPoolModule {
25 struct GroupInfo {
26 public:
GetFailedIndexGroupInfo27     int32_t GetFailedIndex()
28     {
29         return failedIndex;
30     }
31 
SetFailedIndexGroupInfo32     void SetFailedIndex(int32_t index)
33     {
34         failedIndex = index;
35     }
36 
HasExceptionGroupInfo37     bool HasException()
38     {
39         return failedIndex != -1;
40     }
41 
42     uint32_t finishedTaskNum {};
43     napi_ref resArr {nullptr};
44     Priority priority {Priority::DEFAULT};
45     napi_deferred deferred {nullptr};
46 
47 private:
48     int32_t failedIndex {-1}; // -1: the initial value means no exception
49 };
50 
51 class TaskGroup {
52 public:
53     TaskGroup() = default;
54     ~TaskGroup() = default;
55 
56     static napi_value TaskGroupConstructor(napi_env env, napi_callback_info cbinfo);
57     static napi_value AddTask(napi_env env, napi_callback_info cbinfo);
58     static void HostEnvCleanupHook(void* data);
59 
60     uint32_t GetTaskIndex(uint32_t taskId);
61     void NotifyGroupTask(napi_env env);
62     void CancelPendingGroup(napi_env env);
63     void CancelGroupTask(napi_env env, uint64_t taskId);
64     void RejectResult(napi_env env, napi_value res);
65 
66 private:
67     TaskGroup(const TaskGroup &) = delete;
68     TaskGroup& operator=(const TaskGroup &) = delete;
69     TaskGroup(TaskGroup &&) = delete;
70     TaskGroup& operator=(TaskGroup &&) = delete;
71 
72     static void TaskGroupDestructor(napi_env env, void* data, void* hint);
73 
74     friend class NativeEngineTest;
75 public:
76     uint64_t groupId_ {};
77     GroupInfo* currentGroupInfo_ {};
78     std::list<GroupInfo*> pendingGroupInfos_ {};
79     std::list<napi_ref> taskRefs_ {};
80     std::list<uint64_t> taskIds_ {};
81     uint32_t taskNum_ {};
82     std::atomic<ExecuteState> groupState_ {ExecuteState::NOT_FOUND};
83     napi_ref groupRef_ {};
84     RECURSIVE_MUTEX taskGroupMutex_ {};
85     std::atomic<bool> isValid_ {true};
86 };
87 } // namespace Commonlibrary::Concurrent::TaskPoolModule
88 #endif // JS_CONCURRENT_MODULE_TASKPOOL_TASK_GROUP_H
89