js-apis-taskpool.md 26.7 KB
Newer Older
1
# @ohos.taskpool (Starting the Task Pool)
G
Gloria 已提交
2 3 4

The 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.

5
You 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**.
G
Gloria 已提交
6

7
If 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.
G
Gloria 已提交
8 9 10 11 12 13 14 15

The **TaskPool** APIs return error codes in numeric format. For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

> **NOTE**<br>
> 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.

## Modules to Import

G
Gloria 已提交
16
```ts
G
Gloria 已提交
17 18 19 20 21
import taskpool from '@ohos.taskpool';
```

## Priority

G
Gloria 已提交
22
Enumerates the priorities available for created tasks.
G
Gloria 已提交
23 24 25 26 27 28 29 30 31

**System capability**: SystemCapability.Utils.Lang

| Name| Value| Description|
| -------- | -------- | -------- |
| HIGH   | 0    | The task has a high priority.|
| MEDIUM | 1 | The task has a medium priority.|
| LOW | 2 | The task has a low priority.|

G
Gloria 已提交
32 33 34
**Example**

```ts
35 36 37
@Concurrent
function printArgs(args) {
    console.log("printArgs: " + args);
G
Gloria 已提交
38 39
    return args;
}
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

let task = new taskpool.Task(printArgs, 100); // 100: test number
let highCount = 0;
let mediumCount = 0;
let lowCount = 0;
let allCount = 100;
for (let i = 0; i < allCount; i++) {
  taskpool.execute(task, taskpool.Priority.LOW).then((res: number) => {
    lowCount++;
    console.log("taskpool lowCount is :" + lowCount);
  }).catch((e) => {
    console.error("low task error: " + e);
  })
  taskpool.execute(task, taskpool.Priority.MEDIUM).then((res: number) => {
    mediumCount++;
    console.log("taskpool mediumCount is :" + mediumCount);
  }).catch((e) => {
    console.error("medium task error: " + e);
  })
  taskpool.execute(task, taskpool.Priority.HIGH).then((res: number) => {
    highCount++;
    console.log("taskpool highCount is :" + highCount);
  }).catch((e) => {
    console.error("high task error: " + e);
  })
G
Gloria 已提交
65 66 67
}
```

G
Gloria 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
## Task

Implements a task. Before using any of the following APIs, you must create a **Task** instance.

### constructor

constructor(func: Function, ...args: unknown[])

A constructor used to create a **Task** instance.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name| Type     | Mandatory| Description                                                                 |
| ------ | --------- | ---- | -------------------------------------------------------------------- |
| 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).  |
G
Gloria 已提交
85
| 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**.|
G
Gloria 已提交
86 87 88 89 90

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

91
| ID| Error Message                                |
G
Gloria 已提交
92 93 94 95 96
| -------- | --------------------------------------- |
| 10200014 | The function is not mark as concurrent. |

**Example**

G
Gloria 已提交
97 98
```ts
@Concurrent
99 100
function printArgs(args) {
    console.log("printArgs: " + args);
G
Gloria 已提交
101 102
    return args;
}
G
Gloria 已提交
103

104
let task = new taskpool.Task(printArgs, "this is my first Task");
G
Gloria 已提交
105 106
```

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
### isCanceled<sup>10+</sup>

static isCanceled(): boolean

Checks whether the running task is canceled.

**System capability**: SystemCapability.Utils.Lang

**Return value**

| Type   | Description                                |
| ------- | ------------------------------------ |
| boolean | Returns **true** if the running task is canceled; returns **false** otherwise.|

**Example**

```ts
@Concurrent
function inspectStatus(arg) {
    // do something
    if (taskpool.Task.isCanceled()) {
      console.log("task has been canceled.");
      // do something
      return arg + 1;
    }
    // do something
    return arg;
}
```

> **NOTE**
> 
> **isCanceled** must be used together with **taskpool.cancel**. If **cancel** is not called, **isCanceled** returns **false** by default.

**Example**

```ts
@Concurrent
function inspectStatus(arg) {
    // Check the cancellation status and return the result.
    if (taskpool.Task.isCanceled()) {
      console.log("task has been canceled before 2s sleep.");
      return arg + 2;
    }
    // Wait for 2s.
    let t = Date.now();
    while (Date.now() - t < 2000) {
      continue;
    }
    // Check the cancellation status again and return the result.
    if (taskpool.Task.isCanceled()) {
      console.log("task has been canceled after 2s sleep.");
      return arg + 3;
    }
  return arg + 1;
}

let task = new taskpool.Task(inspectStatus, 100); // 100: test number
taskpool.execute(task).then((res)=>{
  console.log("taskpool test result: " + res);
}).catch((err) => {
  console.log("taskpool test occur error: " + err);
});
// If cancel is not called, isCanceled() returns false by default, and the task execution result is 101.
```

### setTransferList<sup>10+</sup>

setTransferList(transfer?: ArrayBuffer[]): void

Sets the task transfer list.

> **NOTE**
> 
> This API is used to set the task transfer list in the form of **ArrayBuffer** in the task pool. The **ArrayBuffer** instance does not copy the content in the task to the worker thread during transfer. Instead, it transfers the buffer control right to the worker thread. After the transfer, the **ArrayBuffer** instance becomes invalid.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name  | Type          | Mandatory| Description                                         |
| -------- | ------------- | ---- | --------------------------------------------- |
| transfer | ArrayBuffer[] | No  | **ArrayBuffer** instance holding the objects to transfer. The default value is an empty array.|

**Example**

```ts
let buffer = new ArrayBuffer(8);
let view = new Uint8Array(buffer);
let buffer1 = new ArrayBuffer(16);
let view1 = new Uint8Array(buffer1);

console.info("testTransfer view byteLength: " + view.byteLength);
console.info("testTransfer view1 byteLength: " + view1.byteLength);
@Concurrent
function testTransfer(arg1, arg2) {
  console.info("testTransfer arg1 byteLength: " + arg1.byteLength);
  console.info("testTransfer arg2 byteLength: " + arg2.byteLength);
  return 100;
}
let task = new taskpool.Task(testTransfer, view, view1);
task.setTransferList([view.buffer, view1.buffer]);
taskpool.execute(task).then((res)=>{
  console.info("test result: " + res);
}).catch((e)=>{
  console.error("test catch: " + e);
})
console.info("testTransfer view byteLength: " + view.byteLength);
console.info("testTransfer view1 byteLength: " + view1.byteLength);
```

G
Gloria 已提交
218 219 220 221 222 223 224 225 226
### Attributes

**System capability**: SystemCapability.Utils.Lang

| Name     | Type     | Readable| Writable| Description                                                                      |
| --------- | --------- | ---- | ---- | ------------------------------------------------------------------------- |
| 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).  |
| arguments | unknown[] | Yes  | Yes  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).|

227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
## TaskGroup<sup>10+</sup>

Implements a task group. Before using any of the following APIs, you must create a **TaskGroup** instance.

### constructor<sup>10+</sup>

constructor()

Constructor used to create a **TaskGroup** instance.

**System capability**: SystemCapability.Utils.Lang

**Example**

```ts
let taskGroup = new taskpool.TaskGroup();
```

### addTask<sup>10+</sup>

addTask(func: Function, ...args: unknown[]): void

Adds the function to be executed to this task group.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name| Type     | Mandatory| Description                                                                  |
| ------ | --------- | ---- | ---------------------------------------------------------------------- |
| 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).    |
| 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**.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                |
| -------- | --------------------------------------- |
| 10200014 | The function is not mark as concurrent. |

**Example**

```ts
@Concurrent
function printArgs(args) {
    console.log("printArgs: " + args);
    return args;
}

let taskGroup = new taskpool.TaskGroup();
taskGroup.addTask(printArgs, 100); // 100: test number
```

### addTask<sup>10+</sup>

addTask(task: Task): void

Adds a created task to this task group.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name  | Type                 | Mandatory| Description                                      |
| -------- | --------------------- | ---- | ---------------------------------------- |
| task     | [Task](#task)         | Yes  | Task to be added to the task group.                 |

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                |
| -------- | --------------------------------------- |
| 10200014 | The function is not mark as concurrent. |

**Example**

```ts
@Concurrent
function printArgs(args) {
    console.log("printArgs: " + args);
    return args;
}

let taskGroup = new taskpool.TaskGroup();
let task = new taskpool.Task(printArgs, 200); // 200: test number
taskGroup.addTask(task);
```

G
Gloria 已提交
317 318 319 320
## taskpool.execute

execute(func: Function, ...args: unknown[]): Promise\<unknown>

G
Gloria 已提交
321
Places 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.
G
Gloria 已提交
322 323 324 325 326 327 328

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name| Type     | Mandatory| Description                                                                  |
| ------ | --------- | ---- | ---------------------------------------------------------------------- |
G
Gloria 已提交
329 330
| 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).    |
| 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**.|
G
Gloria 已提交
331 332 333 334 335 336 337 338 339 340 341

**Return value**

| Type             | Description                                |
| ----------------- | ------------------------------------ |
| Promise\<unknown> | Promise used to return the result.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

342 343 344 345 346
| ID| Error Message                                     |
| -------- | -------------------------------------------- |
| 10200003 | Worker initialization failure.               |
| 10200006 | An exception occurred during serialization.  |
| 10200014 | The function is not mark as concurrent.      |
G
Gloria 已提交
347 348 349

**Example**

G
Gloria 已提交
350 351
```ts
@Concurrent
352 353
function printArgs(args) {
    console.log("printArgs: " + args);
G
Gloria 已提交
354 355 356
    return args;
}

357
taskpool.execute(printArgs, 100).then((value) => { // 100: test number
G
Gloria 已提交
358
  console.log("taskpool result: " + value);
359
});
G
Gloria 已提交
360 361 362 363 364 365
```

## taskpool.execute

execute(task: Task, priority?: Priority): Promise\<unknown>

G
Gloria 已提交
366
Places 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.
G
Gloria 已提交
367 368 369 370 371

**System capability**: SystemCapability.Utils.Lang

**Parameters**

G
Gloria 已提交
372 373 374
| Name  | Type                 | Mandatory| Description                                      |
| -------- | --------------------- | ---- | ---------------------------------------- |
| task     | [Task](#task)         | Yes  | Task to be executed.                 |
375
| priority | [Priority](#priority) | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
G
Gloria 已提交
376 377 378

**Return value**

379 380
| Type             | Description             |
| ----------------  | ---------------- |
G
Gloria 已提交
381 382 383 384 385 386
| Promise\<unknown> | Promise used to return the result.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

387 388 389 390 391
| ID| Error Message                                    |
| -------- | ------------------------------------------- |
| 10200003 | Worker initialization failure.              |
| 10200006 | An exception occurred during serialization. |
| 10200014 | The function is not mark as concurrent.     |
G
Gloria 已提交
392 393 394

**Example**

G
Gloria 已提交
395 396
```ts
@Concurrent
397 398
function printArgs(args) {
    console.log("printArgs: " + args);
G
Gloria 已提交
399 400
    return args;
}
G
Gloria 已提交
401

402 403
let task = new taskpool.Task(printArgs, 100); // 100: test number
taskpool.execute(task).then((value) => {
G
Gloria 已提交
404
  console.log("taskpool result: " + value);
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
});
```

## taskpool.execute<sup>10+</sup>

execute(group: TaskGroup, priority?: Priority): Promise<unknown[]>

Places a task group in the internal task queue of the task pool. The task group will be distributed to the worker thread for execution.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name    | Type                       | Mandatory| Description                                                          |
| --------- | --------------------------- | ---- | -------------------------------------------------------------- |
| group     | [TaskGroup](#taskgroup)     | Yes  | Task group to be executed.                                     |
| priority  | [Priority](#priority)       | No  | Priority of the task group. The default value is **taskpool.Priority.MEDIUM**.|

**Return value**

| Type                | Description                              |
| ----------------    | ---------------------------------- |
| Promise\<unknown[]> | Promise used to return the result.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                    |
| -------- | ------------------------------------------- |
| 10200006 | An exception occurred during serialization. |

**Example**

```ts
@Concurrent
function printArgs(args) {
    console.log("printArgs: " + args);
    return args;
G
Gloria 已提交
444 445
}

446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
let taskGroup1 = new taskpool.TaskGroup();
taskGroup1.addTask(printArgs, 10); // 10: test number
taskGroup1.addTask(printArgs, 20); // 20: test number
taskGroup1.addTask(printArgs, 30); // 30: test number

let taskGroup2 = new taskpool.TaskGroup();
let task1 = new taskpool.Task(printArgs, 100); // 100: test number
let task2 = new taskpool.Task(printArgs, 200); // 200: test number
let task3 = new taskpool.Task(printArgs, 300); // 300: test number
taskGroup2.addTask(task1);
taskGroup2.addTask(task2);
taskGroup2.addTask(task3);
taskpool.execute(taskGroup1).then((res) => {
  console.info("taskpool execute res is:" + res);
}).catch((e) => {
  console.error("taskpool execute error is:" + e);
});
taskpool.execute(taskGroup2).then((res) => {
  console.info("taskpool execute res is:" + res);
}).catch((e) => {
  console.error("taskpool execute error is:" + e);
});
G
Gloria 已提交
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
```

## taskpool.cancel

cancel(task: Task): void

Cancels a task in the task pool.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name| Type         | Mandatory| Description                |
| ------ | ------------- | ---- | -------------------- |
| task   | [Task](#task) | Yes  | Task to cancel.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

488 489 490 491
| ID| Error Message                                     |
| -------- | -------------------------------------------- |
| 10200015 | The task does not exist when it is canceled. |
| 10200016 | The task is executing when it is canceled.   |
G
Gloria 已提交
492

493 494 495
Since API version 10, error code 10200016 is not reported when this API is called.

**Example of canceling an ongoing task**
G
Gloria 已提交
496

G
Gloria 已提交
497
```ts
498
@Concurrent
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
function inspectStatus(arg) {
    // Check the task cancellation state and return the result.
    if (taskpool.Task.isCanceled()) {
      console.log("task has been canceled before 2s sleep.");
      return arg + 2;
    }
    // 2s sleep
    let t = Date.now();
    while (Date.now() - t < 2000) {
      continue;
    }
    // Check the task cancellation state again and return the result.
    if (taskpool.Task.isCanceled()) {
      console.log("task has been canceled after 2s sleep.");
      return arg + 3;
    }
    return arg + 1;
G
Gloria 已提交
516 517
}

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
let task1 = new taskpool.Task(inspectStatus, 100); // 100: test number
let task2 = new taskpool.Task(inspectStatus, 200); // 200: test number
let task3 = new taskpool.Task(inspectStatus, 300); // 300: test number
let task4 = new taskpool.Task(inspectStatus, 400); // 400: test number
let task5 = new taskpool.Task(inspectStatus, 500); // 500: test number
let task6 = new taskpool.Task(inspectStatus, 600); // 600: test number
taskpool.execute(task1).then((res)=>{
  console.log("taskpool test result: " + res);
}).catch((err) => {
  console.log("taskpool test occur error: " + err);
});
let res2 = taskpool.execute(task2);
let res3 = taskpool.execute(task3);
let res4 = taskpool.execute(task4);
let res5 = taskpool.execute(task5);
let res6 = taskpool.execute(task6);
// Cancel the task 1s later.
setTimeout(()=>{
  taskpool.cancel(task1);}, 1000);
G
Gloria 已提交
537 538
```

539
## taskpool.cancel<sup>10+</sup>
G
Gloria 已提交
540

541
cancel(group: TaskGroup): void
G
Gloria 已提交
542

543
Cancels a task group in the task pool.
G
Gloria 已提交
544

545
**System capability**: SystemCapability.Utils.Lang
G
Gloria 已提交
546

547 548 549 550 551 552 553 554 555
**Parameters**

| Name  | Type                   | Mandatory| Description                |
| ------- | ----------------------- | ---- | -------------------- |
| group   | [TaskGroup](#taskgroup) | Yes  | Task group to cancel.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
G
Gloria 已提交
556

557 558 559 560 561
| ID| Error Message                                                |
| -------- | ------------------------------------------------------- |
| 10200018 | The task group does not exist when it is canceled.      |

**Example**
G
Gloria 已提交
562 563

```ts
564 565
@Concurrent
function printArgs(args) {
566 567 568 569
    let t = Date.now();
    while (Date.now() - t < 2000) {
      continue;
    }
570
    console.log("printArgs: " + args);
G
Gloria 已提交
571 572 573
    return args;
}

574 575 576 577 578 579 580 581 582 583 584
let taskGroup1 = new taskpool.TaskGroup();
taskGroup1.addTask(printArgs, 10); // 10: test number
let taskGroup2 = new taskpool.TaskGroup();
taskGroup2.addTask(printArgs, 100); // 100: test number
taskpool.execute(taskGroup1).then((res)=>{
  console.info("taskGroup1 res is:" + res)
});
taskpool.execute(taskGroup2).then((res)=>{
  console.info("taskGroup2 res is:" + res)
});
setTimeout(()=>{
G
Gloria 已提交
585
  try {
586
    taskpool.cancel(taskGroup2);
G
Gloria 已提交
587
  } catch (e) {
588
    console.log("taskGroup.cancel occur error:" + e);
G
Gloria 已提交
589
  }
590
}, 1000);
G
Gloria 已提交
591 592
```

G
Gloria 已提交
593 594 595 596 597 598
## Additional Information

### Sequenceable Data Types
The following sequenceable data types are supported: All Primitive Type (excluding symbol), Date, String, RegExp, Array, Map, Set, Object, ArrayBuffer, and TypedArray.

### Precautions
G
Gloria 已提交
599 600 601
- 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**.
- 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.
- 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.
602
- The decorator **@Concurrent** can be used only in .ets files.
G
Gloria 已提交
603

G
Gloria 已提交
604 605 606 607 608 609 610
### Using the Task Pool in Simple Mode

**Example 1**

```ts
// Common functions are supported, and variables passed in by input parameters are also supported.
@Concurrent
611
function printArgs(args) {
G
Gloria 已提交
612 613 614 615
    console.log("func: " + args);
    return args;
}

616
async function taskpoolExecute() {
G
Gloria 已提交
617
  // taskpool.execute(task)
618
  let task = new taskpool.Task(printArgs, "create task, then execute");
G
Gloria 已提交
619 620
  let val1 = await taskpool.execute(task);
  console.log("taskpool.execute(task) result: " + val1);
G
Gloria 已提交
621

G
Gloria 已提交
622
  // taskpool.execute(function)
623
  let val2 = await taskpool.execute(printArgs, "execute task by func");
G
Gloria 已提交
624 625 626
  console.log("taskpool.execute(function) result: " + val2);
}

627
taskpoolExecute();
G
Gloria 已提交
628 629
```

G
Gloria 已提交
630
**Example 2**
G
Gloria 已提交
631

G
Gloria 已提交
632 633
```ts
// b.ets
634
export let c = 2000;
G
Gloria 已提交
635 636 637 638 639
```
```ts
// Reference an imported variable.
// a.ets (in the same directory as b.ets)
import { c } from "./b";
G
Gloria 已提交
640

G
Gloria 已提交
641
@Concurrent
642
function printArgs(a) {
G
Gloria 已提交
643 644 645 646 647
    console.log(a);
    console.log(c);
    return a;
}

648
async function taskpoolExecute() {
G
Gloria 已提交
649
  // taskpool.execute(task)
650
  let task = new taskpool.Task(printArgs, "create task, then execute");
G
Gloria 已提交
651 652 653 654
  let val1 = await taskpool.execute(task);
  console.log("taskpool.execute(task) result: " + val1);

  // taskpool.execute(function)
655
  let val2 = await taskpool.execute(printArgs, "execute task by func");
G
Gloria 已提交
656 657
  console.log("taskpool.execute(function) result: " + val2);
}
G
Gloria 已提交
658

659
taskpoolExecute();
G
Gloria 已提交
660
```
G
Gloria 已提交
661 662 663 664 665 666

**Example 3**

```ts
// The async functions are supported.
@Concurrent
667
async function delayExcute() {
G
Gloria 已提交
668 669 670 671 672 673
  let ret = await Promise.all([
    new Promise(resolve => setTimeout(resolve, 1000, "resolved"))
  ]);
  return ret;
}

674 675
async function taskpoolExecute() {
  taskpool.execute(delayExcute).then((result) => {
G
Gloria 已提交
676 677 678 679
    console.log("TaskPoolTest task result: " + result);
  });
}

680
taskpoolExecute();
G
Gloria 已提交
681 682 683 684 685
```

**Example 4**

```ts
686 687 688 689 690
// c.ets
@Concurrent
function strSort(inPutArr) {
  let newArr = inPutArr.sort();
  return newArr;
G
Gloria 已提交
691
}
692 693 694
export async function func1() {
    console.log("taskpoolTest start");
    let strArray = ['c test string', 'b test string', 'a test string'];
695 696
    let task = new taskpool.Task(strSort, strArray);
    let result = await taskpool.execute(task);
697
    console.log("func1 result:" + result);
G
Gloria 已提交
698 699
}

700
export async function func2() {
G
Gloria 已提交
701
    console.log("taskpoolTest2 start");
702 703 704
    let strArray = ['c test string', 'b test string', 'a test string'];
    taskpool.execute(strSort, strArray).then((result) => {
        console.log("func2 result: " + result);
G
Gloria 已提交
705 706 707 708 709
    });
}
```

```ts
710
// a.ets (in the same directory as c.ets)
G
Gloria 已提交
711 712
import { taskpoolTest1, taskpoolTest2 } from "./c";

713 714
func1();
func2();
G
Gloria 已提交
715
```
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838

**Example 5**

```ts
// Success in canceling a task
@Concurrent
function inspectStatus(arg) {
    // Check the task cancellation state and return the result.
    if (taskpool.Task.isCanceled()) {
      console.log("task has been canceled before 2s sleep.");
      return arg + 2;
    }
    // Wait for 2s.
    let t = Date.now();
    while (Date.now() - t < 2000) {
      continue;
    }
    // Check the task cancellation state again and return the result.
    if (taskpool.Task.isCanceled()) {
      console.log("task has been canceled after 2s sleep.");
      return arg + 3;
    }
    return arg + 1;
}

async function taskpoolCancel() {
    let task = new taskpool.Task(inspectStatus, 100); // 100: test number
    taskpool.execute(task).then((res)=>{
      console.log("taskpool test result: " + res);
    }).catch((err) => {
      console.log("taskpool test occur error: " + err);
    });
    // Cancel the task 1s later.
    setTimeout(()=>{
      taskpool.cancel(task);}, 1000);
}

taskpoolCancel();
```

**Example 6**

```ts
// Failure to cancel a task that has been executed
@Concurrent
function inspectStatus(arg) {
    // Check the cancellation status and return the result.
    if (taskpool.Task.isCanceled()) {
      return arg + 2;
    }
    // Wait for 2s.
    let t = Date.now();
    while (Date.now() - t < 2000) {
      continue;
    }
    // Check the cancellation status again and return the result.
    if (taskpool.Task.isCanceled()) {
      return arg + 3;
    }
    return arg + 1;
}

async function taskpoolCancel() {
    let task = new taskpool.Task(inspectStatus, 100); // 100: test number
    taskpool.execute(task).then((res)=>{
      console.log("taskpool test result: " + res);
    }).catch((err) => {
      console.log("taskpool test occur error: " + err);
    });
    setTimeout(()=>{
      try {
        taskpool.cancel(task); // The task has been executed and fails to be canceled.
      } catch (e) {
        console.log("taskpool.cancel occur error:" + e);
      }
    }, 3000); // Wait for 3s to ensure that the task has been executed.
}

taskpoolCancel();
```

**Example 7**

```ts
// Success of canceling a task group to be executed
@Concurrent
function printArgs(args) {
  let t = Date.now();
  while (Date.now() - t < 1000) {
    continue;
  }
  console.log("printArgs: " + args);
  return args;
}

async function taskpoolGroupCancelTest() {
  let taskGroup1 = new taskpool.TaskGroup();
  taskGroup1.addTask(printArgs, 10); // 10: test number
  taskGroup1.addTask(printArgs, 20); // 20: test number
  taskGroup1.addTask(printArgs, 30); // 30: test number
  let taskGroup2 = new taskpool.TaskGroup();
  let task1 = new taskpool.Task(printArgs, 100); // 100: test number
  let task2 = new taskpool.Task(printArgs, 200); // 200: test number
  let task3 = new taskpool.Task(printArgs, 300); // 300: test number
  taskGroup2.addTask(task1);
  taskGroup2.addTask(task2);
  taskGroup2.addTask(task3);
  taskpool.execute(taskGroup1).then((res) => {
    console.info("taskpool execute res is:" + res);
  }).catch((e) => {
    console.error("taskpool execute error is:" + e);
  });
  taskpool.execute(taskGroup2).then((res) => {
    console.info("taskpool execute res is:" + res);
  }).catch((e) => {
    console.error("taskpool execute error is:" + e);
  });

  taskpool.cancel(taskGroup2);
}

taskpoolGroupCancelTest()
```