• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 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 #include "task.h"
17 
18 #include "helper/error_helper.h"
19 #include "helper/object_helper.h"
20 #include "task_manager.h"
21 
22 namespace Commonlibrary::Concurrent::TaskPoolModule {
23 using namespace Commonlibrary::Concurrent::Common::Helper;
24 
TaskConstructor(napi_env env,napi_callback_info cbinfo)25 napi_value Task::TaskConstructor(napi_env env, napi_callback_info cbinfo)
26 {
27     // check argv count
28     size_t argc = 0;
29     napi_get_cb_info(env, cbinfo, &argc, nullptr, nullptr, nullptr);
30     if (argc < 1) {
31         ErrorHelper::ThrowError(env, ErrorHelper::TYPE_ERROR, "taskpool:: create task need more than one param");
32         return nullptr;
33     }
34 
35     // check 1st param is func
36     napi_value thisVar = nullptr;
37     void* data = nullptr;
38     napi_value* args = new napi_value[argc];
39     ObjectScope<napi_value> scope(args, true);
40     napi_get_cb_info(env, cbinfo, &argc, args, &thisVar, &data);
41     napi_valuetype type;
42     NAPI_CALL(env, napi_typeof(env, args[0], &type));
43     if (type != napi_function) {
44         ErrorHelper::ThrowError(env, ErrorHelper::TYPE_ERROR, "taskpool:: the first param of task must be function");
45         return nullptr;
46     }
47 
48     napi_value argsArray;
49     napi_create_array_with_length(env, argc - 1, &argsArray);
50     for (size_t i = 0; i < argc - 1; i++) {
51         napi_set_element(env, argsArray, i, args[i + 1]);
52     }
53 
54     napi_value object = nullptr;
55     napi_create_object(env, &object);
56     napi_set_named_property(env, object, "func", args[0]);
57     napi_set_named_property(env, object, "args", argsArray);
58 
59     Task* task = new (std::nothrow) Task();
60     napi_ref objRef = nullptr;
61     napi_create_reference(env, object, 1, &objRef);
62     task->objRef_ = objRef;
63     task->taskId_ = TaskManager::GetInstance().GenerateTaskId();
64     napi_wrap(
65         env, thisVar, task,
66         [](napi_env env, void *data, void *hint) {
67             auto obj = reinterpret_cast<Task*>(data);
68             if (obj != nullptr) {
69                 delete obj;
70             }
71         },
72         nullptr, nullptr);
73     return thisVar;
74 }
75 } // namespace Commonlibrary::Concurrent::TaskPoolModule