• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.taskpool (Starting the Task Pool)
2
3The task pool provides a multi-thread running environment for applications. It helps reduce resource consumption and improve system performance. It also frees you from caring about the lifecycle of thread instances. You can use the **TaskPool** APIs to create background tasks and perform operations on them, for example, executing or canceling a task. Theoretically, you can create an unlimited number of tasks, but this is not recommended for memory considerations. In addition, you are not advised performing blocking operations in a task, especially indefinite blocking. Long-time blocking operations occupy worker threads and may block other task scheduling, adversely affecting your application performance.
4
5You can determine the execution sequence of tasks with the same priority. They are executed in the same sequence as you call the task execution APIs. The default task priority is **MEDIUM**. (The task priority mechanism is not supported yet.)
6
7If the number of tasks to be executed is greater than the number of worker threads in the task pool, the task pool scales out based on load balancing to minimize the waiting duration. Similarly, when the number of tasks to be executed falls below the number of worker threads, the task pool scales in to reduce the number of worker threads. (The load balancing mechanism is not supported yet.)
8
9The **TaskPool** APIs return error codes in numeric format. For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
10
11> **NOTE**<br>
12> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
13
14## Modules to Import
15
16```ts
17import taskpool from '@ohos.taskpool';
18```
19
20## Priority
21
22Enumerates the priorities available for created tasks. (This enum is not supported yet.)
23
24**System capability**: SystemCapability.Utils.Lang
25
26| Name| Value| Description|
27| -------- | -------- | -------- |
28| HIGH   | 0    | The task has a high priority.|
29| MEDIUM | 1 | The task has a medium priority.|
30| LOW | 2 | The task has a low priority.|
31
32## Task
33
34Implements a task. Before using any of the following APIs, you must create a **Task** instance.
35
36### constructor
37
38constructor(func: Function, ...args: unknown[])
39
40A constructor used to create a **Task** instance.
41
42**System capability**: SystemCapability.Utils.Lang
43
44**Parameters**
45
46| Name| Type     | Mandatory| Description                                                                 |
47| ------ | --------- | ---- | -------------------------------------------------------------------- |
48| func   | Function  | Yes  | Function to be passed in for task execution. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).  |
49| args   | unknown[] | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
50
51**Error codes**
52
53For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
54
55| ID| Error Message                               |
56| -------- | --------------------------------------- |
57| 10200014 | The function is not mark as concurrent. |
58
59**Example**
60
61```ts
62@Concurrent
63function printArgs(args) {
64    console.log("printArgs: " + args);
65    return args;
66}
67
68let task = new taskpool.Task(printArgs, "this is my first Task");
69```
70
71### Attributes
72
73**System capability**: SystemCapability.Utils.Lang
74
75| Name     | Type     | Readable| Writable| Description                                                                      |
76| --------- | --------- | ---- | ---- | ------------------------------------------------------------------------- |
77| function  | Function  | Yes  | Yes  | Function to be passed in during task creation. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).  |
78| arguments | unknown[] | Yes  | Yes  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).|
79
80## taskpool.execute
81
82execute(func: Function, ...args: unknown[]): Promise\<unknown>
83
84Places the function to be executed in the internal task queue of the task pool. The function will be distributed to the worker thread for execution. The function to be executed in this mode cannot be canceled.
85
86**System capability**: SystemCapability.Utils.Lang
87
88**Parameters**
89
90| Name| Type     | Mandatory| Description                                                                  |
91| ------ | --------- | ---- | ---------------------------------------------------------------------- |
92| func   | Function  | Yes  | Function to be executed. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).    |
93| args   | unknown[] | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
94
95**Return value**
96
97| Type             | Description                                |
98| ----------------- | ------------------------------------ |
99| Promise\<unknown> | Promise used to return the result.|
100
101**Error codes**
102
103For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
104
105| ID| Error Message                                 |
106| -------- | ----------------------------------------- |
107| 10200003 | Worker initialization failure.            |
108| 10200006 | Serializing an uncaught exception failed. |
109| 10200014 | The function is not mark as concurrent.   |
110
111**Example**
112
113```ts
114@Concurrent
115function printArgs(args) {
116    console.log("printArgs: " + args);
117    return args;
118}
119
120async function taskpoolExecute() {
121  let value = await taskpool.execute(printArgs, 100);
122  console.log("taskpool result: " + value);
123}
124
125taskpoolExecute();
126```
127
128## taskpool.execute
129
130execute(task: Task, priority?: Priority): Promise\<unknown>
131
132Places a task in the internal task queue of the task pool. The task will be distributed to the worker thread for execution. The task to be executed in this mode can be canceled.
133
134**System capability**: SystemCapability.Utils.Lang
135
136**Parameters**
137
138| Name  | Type                 | Mandatory| Description                                |
139| -------- | --------------------- | ---- | ------------------------------------ |
140| task     | [Task](#task)         | Yes  | Task to be executed.          |
141| priority | [Priority](#priority) | No  | Priority of the task (not supported yet).|
142
143**Return value**
144
145| Type            | Description                          |
146| ---------------- | ------------------------------ |
147| Promise\<unknown> | Promise used to return the result.|
148
149**Error codes**
150
151For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
152
153| ID| Error Message                                 |
154| -------- | ----------------------------------------- |
155| 10200003 | Worker initialization failure.            |
156| 10200006 | Serializing an uncaught exception failed. |
157| 10200014 | The function is not mark as concurrent.   |
158
159**Example**
160
161```ts
162@Concurrent
163function printArgs(args) {
164    console.log("printArgs: " + args);
165    return args;
166}
167
168async function taskpoolExecute() {
169  let task = new taskpool.Task(printArgs, 100);
170  let value = await taskpool.execute(task);
171  console.log("taskpool result: " + value);
172}
173
174taskpoolExecute();
175```
176
177## taskpool.cancel
178
179cancel(task: Task): void
180
181Cancels a task in the task pool.
182
183**System capability**: SystemCapability.Utils.Lang
184
185**Parameters**
186
187| Name| Type         | Mandatory| Description                |
188| ------ | ------------- | ---- | -------------------- |
189| task   | [Task](#task) | Yes  | Task to cancel.|
190
191**Error codes**
192
193For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
194
195| ID| Error Message                 |
196| -------- | ------------------------- |
197| 10200015 | If the task is not exist. |
198| 10200016 | If the task is running.   |
199
200**Example of successful task cancellation**
201
202```ts
203@Concurrent
204function printArgs(args) {
205    console.log("printArgs: " + args);
206    return args;
207}
208
209async function taskpoolCancel() {
210  let task = new taskpool.Task(printArgs, 100);
211  taskpool.execute(task);
212  try {
213    taskpool.cancel(task);
214  } catch (e) {
215    console.log("taskpool.cancel occur error:" + e);
216  }
217}
218
219taskpoolCancel();
220```
221
222**Example of a failure to cancel a task that has been executed**
223
224```ts
225@Concurrent
226function printArgs(args) {
227    console.log("printArgs: " + args);
228    return args;
229}
230
231async function taskpoolCancel() {
232  let task = new taskpool.Task(printArgs, 100);
233  let value = taskpool.execute(task);
234  let start = new Date().getTime();
235  while (new Date().getTime() - start < 1000) {// Wait for 1s to ensure that the task has been executed.
236    continue;
237  }
238
239  try {
240    taskpool.cancel(task); // The task has been executed and fails to be canceled.
241  } catch (e) {
242    console.log("taskpool.cancel occur error:" + e);
243  }
244}
245
246taskpoolCancel();
247```
248
249**Example of a failure to cancel an ongoing task**
250
251```ts
252@Concurrent
253function printArgs(args) {
254    console.log("printArgs: " + args);
255    return args;
256}
257
258async function taskpoolCancel() {
259  let task1 = new taskpool.Task(printArgs, 100);
260  let task2 = new taskpool.Task(printArgs, 200);
261  let task3 = new taskpool.Task(printArgs, 300);
262  let task4 = new taskpool.Task(printArgs, 400);
263  let task5 = new taskpool.Task(printArgs, 500);
264  let task6 = new taskpool.Task(printArgs, 600);
265
266  let res1 = taskpool.execute(task1);
267  let res2 = taskpool.execute(task2);
268  let res3 = taskpool.execute(task3);
269  let res4 = taskpool.execute(task4);
270  let res5 = taskpool.execute(task5);
271  let res6 = taskpool.execute(task6);
272  try {
273    taskpool.cancel(task1); // task1 is being executed and fails to be canceled.
274  } catch (e) {
275    console.log("taskpool.cancel occur error:" + e);
276  }
277}
278
279taskpoolCancel();
280```
281
282## Additional Information
283
284### Sequenceable Data Types
285The following sequenceable data types are supported: All Primitive Type (excluding symbol), Date, String, RegExp, Array, Map, Set, Object, ArrayBuffer, and TypedArray.
286
287### Precautions
288- The task pool APIs can be used only in the module with **compileMode** set to **esmodule** in the stage model. To check the **compileMode** setting of a module, open the **build-profile.json5** file of the module and check for **"compileMode": "esmodule"** under **buildOption**.
289- A task in the task pool can reference only variables passed in by input parameters or imported variables, rather than closure variables. The decorator **@Concurrent** is used to intercept unsupported variables.
290- A task in the task pool supports only common functions or async functions, rather than class member functions or anonymous functions. The decorator **@Concurrent** is used to intercept unsupported functions.
291- The decorator **@Concurrent** can be used only in .ets files.
292
293### Using the Task Pool in Simple Mode
294
295**Example 1**
296
297```ts
298// Common functions are supported, and variables passed in by input parameters are also supported.
299@Concurrent
300function printArgs(args) {
301    console.log("printArgs: " + args);
302    return args;
303}
304
305async function taskpoolExecute() {
306  // taskpool.execute(task)
307  let task = new taskpool.Task(printArgs, "create task, then execute");
308  let val1 = await taskpool.execute(task);
309  console.log("taskpool.execute(task) result: " + val1);
310
311  // taskpool.execute(function)
312  let val2 = await taskpool.execute(func, "execute task by func");
313  console.log("taskpool.execute(function) result: " + val2);
314}
315
316taskpoolExecute();
317```
318
319**Example 2**
320
321```ts
322// b.ets
323export var c = 2000;
324```
325```ts
326// Reference an imported variable.
327// a.ets (in the same directory as b.ets)
328import { c } from "./b";
329
330@Concurrent
331function printArgs(a) {
332    console.log(a);
333    console.log(c);
334    return a;
335}
336
337async function taskpoolExecute() {
338  // taskpool.execute(task)
339  let task = new taskpool.Task(printArgs, "create task, then execute");
340  let val1 = await taskpool.execute(task);
341  console.log("taskpool.execute(task) result: " + val1);
342
343  // taskpool.execute(function)
344  let val2 = await taskpool.execute(printArgs, "execute task by func");
345  console.log("taskpool.execute(function) result: " + val2);
346}
347
348taskpoolExecute();
349```
350
351**Example 3**
352
353```ts
354// The async functions are supported.
355@Concurrent
356async function delayExcute() {
357  let ret = await Promise.all([
358    new Promise(resolve => setTimeout(resolve, 1000, "resolved"))
359  ]);
360  return ret;
361}
362
363async function taskpoolExecute() {
364  taskpool.execute(delayExcute).then((result) => {
365    console.log("TaskPoolTest task result: " + result);
366  });
367}
368
369taskpoolExecute();
370```
371
372**Example 4**
373
374```ts
375// c.ets
376@Concurrent
377function strSort(inPutArr) {
378  let newArr = inPutArr.sort();
379  return newArr;
380}
381export async function func1() {
382    console.log("taskpoolTest start");
383    let strArray = ['c test string', 'b test string', 'a test string'];
384    var task = new taskpool.Task(strSort, strArray);
385    var result = await taskpool.execute(task);
386    console.log("func1 result:" + result);
387}
388
389export async function func2() {
390    console.log("taskpoolTest2 start");
391    let strArray = ['c test string', 'b test string', 'a test string'];
392    taskpool.execute(strSort, strArray).then((result) => {
393        console.log("func2 result: " + result);
394    });
395}
396```
397
398```ts
399/ / a.ets (in the same directory as c.ets)
400import { taskpoolTest1, taskpoolTest2 } from "./c";
401
402func1();
403func2();
404```
405