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**. 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. 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 11For details about the precautions for using **TaskPool**, see [Precautions for TaskPool](../../arkts-utils/taskpool-introduction.md#precautions-for-taskpool). 12 13> **NOTE**<br> 14> 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. 15 16## Modules to Import 17 18```ts 19import taskpool from '@ohos.taskpool'; 20``` 21## taskpool.execute 22 23execute(func: Function, ...args: unknown[]): Promise\<unknown> 24 25Places 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. 26 27**System capability**: SystemCapability.Utils.Lang 28 29**Parameters** 30 31| Name| Type | Mandatory| Description | 32| ------ | --------- | ---- | ---------------------------------------------------------------------- | 33| 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). | 34| 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**.| 35 36**Return value** 37 38| Type | Description | 39| ----------------- | ------------------------------------ | 40| Promise\<unknown> | Promise used to return the result.| 41 42**Error codes** 43 44For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). 45 46| ID| Error Message | 47| -------- | -------------------------------------------- | 48| 10200003 | Worker initialization failure. | 49| 10200006 | An exception occurred during serialization. | 50| 10200014 | The function is not mark as concurrent. | 51 52**Example** 53 54```ts 55@Concurrent 56function printArgs(args: number): number { 57 console.log("printArgs: " + args); 58 return args; 59} 60 61taskpool.execute(printArgs, 100).then((value: number) => { // 100: test number 62 console.log("taskpool result: " + value); 63}); 64``` 65 66## taskpool.execute 67 68execute(task: Task, priority?: Priority): Promise\<unknown> 69 70Places 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. 71 72**System capability**: SystemCapability.Utils.Lang 73 74**Parameters** 75 76| Name | Type | Mandatory| Description | 77| -------- | --------------------- | ---- | ---------------------------------------- | 78| task | [Task](#task) | Yes | Task to be executed. | 79| priority | [Priority](#priority) | No | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.| 80 81**Return value** 82 83| Type | Description | 84| ---------------- | ---------------- | 85| Promise\<unknown> | Promise used to return the result.| 86 87**Error codes** 88 89For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). 90 91| ID| Error Message | 92| -------- | ------------------------------------------- | 93| 10200003 | Worker initialization failure. | 94| 10200006 | An exception occurred during serialization. | 95| 10200014 | The function is not mark as concurrent. | 96 97**Example** 98 99```ts 100@Concurrent 101function printArgs(args: number): number { 102 console.log("printArgs: " + args); 103 return args; 104} 105 106let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number 107taskpool.execute(task).then((value: number) => { 108 console.log("taskpool result: " + value); 109}); 110``` 111 112## taskpool.execute<sup>10+</sup> 113 114execute(group: TaskGroup, priority?: Priority): Promise<unknown[]> 115 116Places a task group in the internal task queue of the task pool. The task group will be distributed to the worker thread for execution. 117 118**System capability**: SystemCapability.Utils.Lang 119 120**Parameters** 121 122| Name | Type | Mandatory| Description | 123| --------- | --------------------------- | ---- | -------------------------------------------------------------- | 124| group | [TaskGroup](#taskgroup10) | Yes | Task group to be executed. | 125| priority | [Priority](#priority) | No | Priority of the task group. The default value is **taskpool.Priority.MEDIUM**.| 126 127**Return value** 128 129| Type | Description | 130| ---------------- | ---------------------------------- | 131| Promise\<unknown[]> | Promise used to return the result.| 132 133**Error codes** 134 135For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). 136 137| ID| Error Message | 138| -------- | ------------------------------------------- | 139| 10200006 | An exception occurred during serialization. | 140 141**Example** 142 143```ts 144@Concurrent 145function printArgs(args: number): number { 146 console.log("printArgs: " + args); 147 return args; 148} 149 150let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup(); 151taskGroup1.addTask(printArgs, 10); // 10: test number 152taskGroup1.addTask(printArgs, 20); // 20: test number 153taskGroup1.addTask(printArgs, 30); // 30: test number 154 155let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup(); 156let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number 157let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number 158let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number 159taskGroup2.addTask(task1); 160taskGroup2.addTask(task2); 161taskGroup2.addTask(task3); 162taskpool.execute(taskGroup1).then((res: Array<number>) => { 163 console.info("taskpool execute res is:" + res); 164}); 165taskpool.execute(taskGroup2).then((res: Array<number>) => { 166 console.info("taskpool execute res is:" + res); 167}); 168``` 169 170## taskpool.cancel 171 172cancel(task: Task): void 173 174Cancels a task in the task pool. 175 176**System capability**: SystemCapability.Utils.Lang 177 178**Parameters** 179 180| Name| Type | Mandatory| Description | 181| ------ | ------------- | ---- | -------------------- | 182| task | [Task](#task) | Yes | Task to cancel.| 183 184**Error codes** 185 186For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). 187 188| ID| Error Message | 189| -------- | -------------------------------------------- | 190| 10200015 | The task does not exist when it is canceled. | 191| 10200016 | The task is executing when it is canceled. | 192 193Since API version 10, error code 10200016 is not reported when this API is called. 194 195**Example of canceling an ongoing task** 196 197```ts 198@Concurrent 199function inspectStatus(arg: number): number { 200 // Check whether the task has been canceled and respond accordingly. 201 if (taskpool.Task.isCanceled()) { 202 console.info("task has been canceled before 2s sleep."); 203 return arg + 2; 204 } 205 // 2s sleep 206 let t: number = Date.now(); 207 while (Date.now() - t < 2000) { 208 continue; 209 } 210 // Check again whether the task has been canceled and respond accordingly. 211 if (taskpool.Task.isCanceled()) { 212 console.info("task has been canceled after 2s sleep."); 213 return arg + 3; 214 } 215 return arg + 1; 216} 217 218function concurrntFunc() { 219 let task1: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number 220 let task2: taskpool.Task = new taskpool.Task(inspectStatus, 200); // 200: test number 221 let task3: taskpool.Task = new taskpool.Task(inspectStatus, 300); // 300: test number 222 let task4: taskpool.Task = new taskpool.Task(inspectStatus, 400); // 400: test number 223 let task5: taskpool.Task = new taskpool.Task(inspectStatus, 500); // 500: test number 224 let task6: taskpool.Task = new taskpool.Task(inspectStatus, 600); // 600: test number 225 taskpool.execute(task1).then((res: Object)=>{ 226 console.info("taskpool test result: " + res); 227 }); 228 taskpool.execute(task2); 229 taskpool.execute(task3); 230 taskpool.execute(task4); 231 taskpool.execute(task5); 232 taskpool.execute(task6); 233 // Cancel the task 1s later. 234 setTimeout(()=>{ 235 try { 236 taskpool.cancel(task1); 237 } catch (e) { 238 console.error(`taskpool: cancel error code: ${e.code}, info: ${e.message}`); 239 } 240 }, 1000); 241} 242 243concurrntFunc(); 244``` 245 246## taskpool.cancel<sup>10+</sup> 247 248cancel(group: TaskGroup): void 249 250Cancels a task group in the task pool. 251 252**System capability**: SystemCapability.Utils.Lang 253 254**Parameters** 255 256| Name | Type | Mandatory| Description | 257| ------- | ----------------------- | ---- | -------------------- | 258| group | [TaskGroup](#taskgroup10) | Yes | Task group to cancel.| 259 260**Error codes** 261 262For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). 263 264| ID| Error Message | 265| -------- | ------------------------------------------------------- | 266| 10200018 | The task group does not exist when it is canceled. | 267 268**Example** 269 270```ts 271@Concurrent 272function printArgs(args: number): number { 273 let t: number = Date.now(); 274 while (Date.now() - t < 2000) { 275 continue; 276 } 277 console.info("printArgs: " + args); 278 return args; 279} 280 281function concurrntFunc() { 282 let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup(); 283 taskGroup1.addTask(printArgs, 10); // 10: test number 284 let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup(); 285 taskGroup2.addTask(printArgs, 100); // 100: test number 286 taskpool.execute(taskGroup1).then((res: Array<Object>)=>{ 287 console.info("taskGroup1 res is:" + res); 288 }); 289 taskpool.execute(taskGroup2).then((res: Array<Object>)=>{ 290 console.info("taskGroup2 res is:" + res); 291 }); 292 setTimeout(()=>{ 293 try { 294 taskpool.cancel(taskGroup2); 295 } catch (e) { 296 console.error(`taskpool: cancel error code: ${e.code}, info: ${e.message}`); 297 } 298 }, 1000); 299} 300 301concurrntFunc(); 302``` 303 304 305## taskpool.getTaskPoolInfo<sup>10+</sup> 306 307getTaskPoolInfo(): TaskPoolInfo 308 309Obtains the internal information about this task pool. 310 311**System capability**: SystemCapability.Utils.Lang 312 313**Return value** 314 315| Type | Description | 316| ----------------------------------- | ------------------ | 317| [TaskPoolInfo](#taskpoolinfo10) | Internal information about the task pool. | 318 319**Example** 320 321```ts 322let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo(); 323``` 324 325## Priority 326 327Enumerates the priorities available for created tasks. 328 329**System capability**: SystemCapability.Utils.Lang 330 331| Name| Value| Description| 332| -------- | -------- | -------- | 333| HIGH | 0 | The task has a high priority.| 334| MEDIUM | 1 | The task has a medium priority.| 335| LOW | 2 | The task has a low priority.| 336 337**Example** 338 339```ts 340@Concurrent 341function printArgs(args: number): number { 342 console.log("printArgs: " + args); 343 return args; 344} 345 346let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number 347let highCount = 0; 348let mediumCount = 0; 349let lowCount = 0; 350let allCount = 100; 351for (let i: number = 0; i < allCount; i++) { 352 taskpool.execute(task, taskpool.Priority.LOW).then((res: number) => { 353 lowCount++; 354 console.log("taskpool lowCount is :" + lowCount); 355 }); 356 taskpool.execute(task, taskpool.Priority.MEDIUM).then((res: number) => { 357 mediumCount++; 358 console.log("taskpool mediumCount is :" + mediumCount); 359 }); 360 taskpool.execute(task, taskpool.Priority.HIGH).then((res: number) => { 361 highCount++; 362 console.log("taskpool highCount is :" + highCount); 363 }); 364} 365``` 366 367## Task 368 369Implements a task. Before calling any APIs in **Task**, you must use [constructor](#constructor) to create a **Task** instance. 370 371### constructor 372 373constructor(func: Function, ...args: unknown[]) 374 375A constructor used to create a **Task** instance. 376 377**System capability**: SystemCapability.Utils.Lang 378 379**Parameters** 380 381| Name| Type | Mandatory| Description | 382| ------ | --------- | ---- | -------------------------------------------------------------------- | 383| 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). | 384| 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**.| 385 386**Error codes** 387 388For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). 389 390| ID| Error Message | 391| -------- | --------------------------------------- | 392| 10200014 | The function is not mark as concurrent. | 393 394**Example** 395 396```ts 397@Concurrent 398function printArgs(args: number): number { 399 console.log("printArgs: " + args); 400 return args; 401} 402 403let task: taskpool.Task = new taskpool.Task(printArgs, "this is my first Task"); 404``` 405 406### isCanceled<sup>10+</sup> 407 408static isCanceled(): boolean 409 410Checks whether the running task is canceled. Before using this API, you must create a **Task** instance. 411 412**System capability**: SystemCapability.Utils.Lang 413 414**Return value** 415 416| Type | Description | 417| ------- | ------------------------------------ | 418| boolean | Returns **true** if the running task is canceled; returns **false** otherwise.| 419 420**Example** 421 422```ts 423@Concurrent 424function inspectStatus(arg: number): number { 425 // do something 426 if (taskpool.Task.isCanceled()) { 427 console.log("task has been canceled."); 428 // do something 429 return arg + 1; 430 } 431 // do something 432 return arg; 433} 434``` 435 436> **NOTE**<br> 437> **isCanceled** must be used together with **taskpool.cancel**. If **cancel** is not called, **isCanceled** returns **false** by default. 438 439**Example** 440 441```ts 442@Concurrent 443function inspectStatus(arg: number): number { 444 // Check the cancellation status and return the result. 445 if (taskpool.Task.isCanceled()) { 446 console.log("task has been canceled before 2s sleep."); 447 return arg + 2; 448 } 449 // Wait for 2s. 450 let t: number = Date.now(); 451 while (Date.now() - t < 2000) { 452 continue; 453 } 454 // Check the cancellation status again and return the result. 455 if (taskpool.Task.isCanceled()) { 456 console.log("task has been canceled after 2s sleep."); 457 return arg + 3; 458 } 459 return arg + 1; 460} 461 462let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number 463taskpool.execute(task).then((res: number)=>{ 464 console.log("taskpool test result: " + res); 465}).catch((err: string) => { 466 console.log("taskpool test occur error: " + err); 467}); 468// If cancel is not called, isCanceled() returns false by default, and the task execution result is 101. 469``` 470 471### setTransferList<sup>10+</sup> 472 473setTransferList(transfer?: ArrayBuffer[]): void 474 475Sets the task transfer list. Before using this API, you must create a **Task** instance. 476 477> **NOTE**<br> 478> 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. An empty **ArrayBuffer** will not be transferred. 479 480**System capability**: SystemCapability.Utils.Lang 481 482**Parameters** 483 484| Name | Type | Mandatory| Description | 485| -------- | ------------- | ---- | --------------------------------------------- | 486| transfer | ArrayBuffer[] | No | **ArrayBuffer** instance holding the objects to transfer. The default value is an empty array.| 487 488**Example** 489 490```ts 491let buffer: ArrayBuffer = new ArrayBuffer(8); 492let view: Uint8Array = new Uint8Array(buffer); 493let buffer1: ArrayBuffer = new ArrayBuffer(16); 494let view1: Uint8Array = new Uint8Array(buffer1); 495 496console.info("testTransfer view byteLength: " + view.byteLength); 497console.info("testTransfer view1 byteLength: " + view1.byteLength); 498@Concurrent 499function testTransfer(arg1: ArrayBuffer, arg2: ArrayBuffer): number { 500 console.info("testTransfer arg1 byteLength: " + arg1.byteLength); 501 console.info("testTransfer arg2 byteLength: " + arg2.byteLength); 502 return 100; 503} 504let task: taskpool.Task = new taskpool.Task(testTransfer, view, view1); 505task.setTransferList([view.buffer, view1.buffer]); 506taskpool.execute(task).then((res: number)=>{ 507 console.info("test result: " + res); 508}).catch((e: string)=>{ 509 console.error("test catch: " + e); 510}) 511console.info("testTransfer view byteLength: " + view.byteLength); 512console.info("testTransfer view1 byteLength: " + view1.byteLength); 513``` 514 515### Attributes 516 517**System capability**: SystemCapability.Utils.Lang 518 519| Name | Type | Readable| Writable| Description | 520| --------- | --------- | ---- | ---- | ------------------------------------------------------------------------- | 521| 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). | 522| arguments | unknown[] | Yes | Yes | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| 523 524## TaskGroup<sup>10+</sup> 525 526Implements a task group, in which all tasks are executed at a time. If all the tasks are executed normally, an array of task results is returned asynchronously, and the sequence of elements in the array is the same as the sequence of tasks added by calling [addTask](#addtask10-1). If any task fails, the corresponding exception is thrown. A task group can be executed for multiple times, but no task can be added after the task group is executed. Before calling any APIs in **TaskGroup**, you must use [constructor](#constructor10) to create a **TaskGroup** instance. 527 528### constructor<sup>10+</sup> 529 530constructor() 531 532Constructor used to create a **TaskGroup** instance. 533 534**System capability**: SystemCapability.Utils.Lang 535 536**Example** 537 538```ts 539let taskGroup = new taskpool.TaskGroup(); 540``` 541 542### addTask<sup>10+</sup> 543 544addTask(func: Function, ...args: unknown[]): void 545 546Adds the function to be executed to this task group. Before using this API, you must create a **TaskGroup** instance. 547 548**System capability**: SystemCapability.Utils.Lang 549 550**Parameters** 551 552| Name| Type | Mandatory| Description | 553| ------ | --------- | ---- | ---------------------------------------------------------------------- | 554| 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). | 555| 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**.| 556 557**Error codes** 558 559For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). 560 561| ID| Error Message | 562| -------- | --------------------------------------- | 563| 10200014 | The function is not mark as concurrent. | 564 565**Example** 566 567```ts 568@Concurrent 569function printArgs(args: number): number { 570 console.log("printArgs: " + args); 571 return args; 572} 573 574let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup(); 575taskGroup.addTask(printArgs, 100); // 100: test number 576``` 577 578### addTask<sup>10+</sup> 579 580addTask(task: Task): void 581 582Adds a created task to this task group. Before using this API, you must create a **TaskGroup** instance. 583 584**System capability**: SystemCapability.Utils.Lang 585 586**Parameters** 587 588| Name | Type | Mandatory| Description | 589| -------- | --------------------- | ---- | ---------------------------------------- | 590| task | [Task](#task) | Yes | Task to be added to the task group. | 591 592**Error codes** 593 594For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). 595 596| ID| Error Message | 597| -------- | --------------------------------------- | 598| 10200014 | The function is not mark as concurrent. | 599 600**Example** 601 602```ts 603@Concurrent 604function printArgs(args: number): number { 605 console.log("printArgs: " + args); 606 return args; 607} 608 609let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup(); 610let task: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number 611taskGroup.addTask(task); 612``` 613 614 615## State<sup>10+</sup> 616 617Enumerates the task states. 618 619**System capability**: SystemCapability.Utils.Lang 620 621| Name | Value | Description | 622| --------- | -------- | ------------- | 623| WAITING | 1 | The task is waiting.| 624| RUNNING | 2 | The task is running.| 625| CANCELED | 3 | The task is canceled.| 626 627 628## TaskInfo<sup>10+</sup> 629 630Describes the internal information about a task. 631 632**System capability**: SystemCapability.Utils.Lang 633 634### Attributes 635 636**System capability**: SystemCapability.Utils.Lang 637 638| Name | Type | Readable| Writable| Description | 639| -------- | ------------------ | ---- | ---- | ------------------------------------------------------------- | 640| taskId | number | Yes | No | Task ID. | 641| state | [State](#state10) | Yes | No | Task state. | 642| duration | number | Yes | No | Duration that the task has been executed, in ms. If the return value is **0**, the task is not running. If the return value is empty, no task is running. | 643 644## ThreadInfo<sup>10+</sup> 645 646Describes the internal information about a worker thread. 647 648**System capability**: SystemCapability.Utils.Lang 649 650### Attributes 651 652**System capability**: SystemCapability.Utils.Lang 653 654| Name | Type | Readable| Writable| Description | 655| -------- | ---------------------- | ---- | ---- | -------------------------------------------------------- | 656| tid | number | Yes | No | ID of the worker thread. If the return value is empty, no task is running. | 657| taskIds | number[] | Yes | No | IDs of tasks running on the calling thread. If the return value is empty, no task is running. | 658| priority | [Priority](#priority) | Yes | No | Priority of the calling thread. If the return value is empty, no task is running. | 659 660## TaskPoolInfo<sup>10+</sup> 661 662Describes the internal information about a task pool. 663 664**System capability**: SystemCapability.Utils.Lang 665 666### Attributes 667 668**System capability**: SystemCapability.Utils.Lang 669 670| Name | Type | Readable| Writable| Description | 671| ------------- | -------------------------------- | ---- | ---- | -------------------- | 672| threadInfos | [ThreadInfo[]](#threadinfo10) | Yes | No | Internal information about the worker threads. | 673| taskInfos | [TaskInfo[]](#taskinfo10) | Yes | No | Internal information about the tasks. | 674 675 676## Additional Information 677 678### Sequenceable Data Types 679The following sequenceable data types are supported: All Primitive Type (excluding symbol), Date, String, RegExp, Array, Map, Set, Object, ArrayBuffer, and TypedArray. 680 681### Using the Task Pool in Simple Mode 682 683**Example 1** 684 685```ts 686// Common functions are supported, and variables passed in by input parameters are also supported. 687@Concurrent 688function printArgs(args: number): number { 689 console.log("func: " + args); 690 return args; 691} 692async function taskpoolExecute(): Promise<void> { 693 // taskpool.execute(task) 694 let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute"); 695 console.log("taskpool.execute(task) result: " + await taskpool.execute(task)); 696 // taskpool.execute(function) 697 console.log("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func")); 698} 699taskpoolExecute(); 700``` 701 702**Example 2** 703 704```ts 705// b.ets 706export let c: string = "hello"; 707``` 708```ts 709// Reference an imported variable. 710// a.ets (in the same directory as b.ets) 711import { c } from "./b"; 712 713@Concurrent 714function printArgs(a: string): string { 715 console.log(a); 716 console.log(c); 717 return a; 718} 719 720async function taskpoolExecute(): Promise<void> { 721 // taskpool.execute(task) 722 let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute"); 723 console.log("taskpool.execute(task) result: " + await taskpool.execute(task)); 724 725 // taskpool.execute(function) 726 console.log("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func")); 727} 728 729taskpoolExecute(); 730``` 731 732**Example 3** 733 734```ts 735// The async functions are supported. 736@Concurrent 737async function delayExcute(): Promise<Object> { 738 let ret = await Promise.all<Object>([ 739 new Promise<Object>(resolve => setTimeout(resolve, 1000, "resolved")) 740 ]); 741 return ret; 742} 743 744async function taskpoolExecute(): Promise<void> { 745 taskpool.execute(delayExcute).then((result: string) => { 746 console.log("taskPoolTest task result: " + result); 747 }).catch((err: string) => { 748 console.log("taskpool test occur error: " + err); 749 }); 750} 751 752taskpoolExecute(); 753``` 754 755**Example 4** 756 757```ts 758// c.ets 759@Concurrent 760function strSort(inPutArr: Array<string>): Array<string> { 761 let newArr = inPutArr.sort(); 762 return newArr; 763} 764export async function func1(): Promise<void> { 765 console.log("taskpoolTest start"); 766 let strArray: Array<string> = ['c test string', 'b test string', 'a test string']; 767 let task: taskpool.Task = new taskpool.Task(strSort, strArray); 768 console.log("func1 result:" + await taskpool.execute(task)); 769} 770 771export async function func2(): Promise<void> { 772 console.log("taskpoolTest2 start"); 773 let strArray: Array<string> = ['c test string', 'b test string', 'a test string']; 774 taskpool.execute(strSort, strArray).then((result: Array<string>) => { 775 console.log("func2 result: " + result); 776 }).catch((err: string) => { 777 console.log("taskpool test occur error: " + err); 778 }); 779} 780``` 781 782```ts 783// a.ets (in the same directory as c.ets) 784import { func1, func2 } from "./c"; 785 786func1(); 787func2(); 788``` 789 790**Example 5** 791 792```ts 793// Success in canceling a task 794@Concurrent 795function inspectStatus(arg: number): number { 796 // Check whether the task has been canceled and respond accordingly. 797 if (taskpool.Task.isCanceled()) { 798 console.info("task has been canceled before 2s sleep."); 799 return arg + 2; 800 } 801 // 2s sleep 802 let t: number = Date.now(); 803 while (Date.now() - t < 2000) { 804 continue; 805 } 806 // Check again whether the task has been canceled and respond accordingly. 807 if (taskpool.Task.isCanceled()) { 808 console.info("task has been canceled after 2s sleep."); 809 return arg + 3; 810 } 811 return arg + 1; 812} 813 814async function taskpoolCancel(): Promise<void> { 815 let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number 816 taskpool.execute(task).then((res: Object)=>{ 817 console.info("taskpool test result: " + res); 818 }).catch((err: string) => { 819 console.error("taskpool test occur error: " + err); 820 }); 821 // Cancel the task 1s later. 822 setTimeout(()=>{ 823 try { 824 taskpool.cancel(task); 825 } catch (e) { 826 console.error(`taskpool: cancel error code: ${e.code}, info: ${e.message}`); 827 } 828 }, 1000); 829} 830 831taskpoolCancel(); 832``` 833 834**Example 6** 835 836```ts 837// Failure to cancel a task that has been executed 838@Concurrent 839function inspectStatus(arg: number): number { 840 // Check whether the task has been canceled and respond accordingly. 841 if (taskpool.Task.isCanceled()) { 842 return arg + 2; 843 } 844 // Wait for 2s. 845 let t: number = Date.now(); 846 while (Date.now() - t < 500) { 847 continue; 848 } 849 // Check again whether the task has been canceled and respond accordingly. 850 if (taskpool.Task.isCanceled()) { 851 return arg + 3; 852 } 853 return arg + 1; 854} 855 856async function taskpoolCancel(): Promise<void> { 857 let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number 858 taskpool.execute(task).then((res: Object)=>{ 859 console.info("taskpool test result: " + res); 860 }).catch((err: string) => { 861 console.error("taskpool test occur error: " + err); 862 }); 863 864 setTimeout(()=>{ 865 try { 866 taskpool.cancel(task); // The task has been executed and fails to be canceled. 867 } catch (e) { 868 console.error(`taskpool: cancel error code: ${e.code}, info: ${e.message}`); 869 } 870 }, 3000); // Wait for 3s to ensure that the task has been executed. 871} 872 873taskpoolCancel(); 874``` 875 876**Example 7** 877 878```ts 879// Success of canceling a task group to be executed 880@Concurrent 881function printArgs(args: number): number { 882 let t: number = Date.now(); 883 while (Date.now() - t < 1000) { 884 continue; 885 } 886 console.log("printArgs: " + args); 887 return args; 888} 889 890async function taskpoolGroupCancelTest(): Promise<void> { 891 let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup(); 892 taskGroup1.addTask(printArgs, 10); // 10: test number 893 taskGroup1.addTask(printArgs, 20); // 20: test number 894 taskGroup1.addTask(printArgs, 30); // 30: test number 895 let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup(); 896 let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number 897 let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number 898 let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number 899 taskGroup2.addTask(task1); 900 taskGroup2.addTask(task2); 901 taskGroup2.addTask(task3); 902 taskpool.execute(taskGroup1).then((res: Array<number>) => { 903 console.info("taskpool execute res is:" + res); 904 }).catch((e: string) => { 905 console.error("taskpool execute error is:" + e); 906 }); 907 taskpool.execute(taskGroup2).then((res: Array<number>) => { 908 console.info("taskpool execute res is:" + res); 909 }).catch((e: string) => { 910 console.error("taskpool execute error is:" + e); 911 }); 912 913 taskpool.cancel(taskGroup2); 914} 915 916taskpoolGroupCancelTest() 917``` 918 919**Example 8** 920 921```ts 922// Create and execute 100 tasks with different priorities, and view their information. 923@Concurrent 924function delay(): void { 925 let start: number = new Date().getTime(); 926 while (new Date().getTime() - start < 500) { 927 continue; 928 } 929} 930 931let highCount: number = 0; 932let mediumCount: number = 0; 933let lowCount: number = 0; 934let allCount: number = 100; 935for (let i = 0; i < allCount; i++) { 936 let task1: taskpool.Task = new taskpool.Task(delay); 937 let task2: taskpool.Task = new taskpool.Task(delay); 938 let task3: taskpool.Task = new taskpool.Task(delay); 939 taskpool.execute(task1, taskpool.Priority.LOW).then(() => { 940 lowCount++; 941 }).catch((e: string) => { 942 console.error("low task error: " + e); 943 }) 944 taskpool.execute(task2, taskpool.Priority.MEDIUM).then(() => { 945 mediumCount++; 946 }).catch((e: string) => { 947 console.error("medium task error: " + e); 948 }) 949 taskpool.execute(task3, taskpool.Priority.HIGH).then(() => { 950 highCount++; 951 }).catch((e: string) => { 952 console.error("high task error: " + e); 953 }) 954} 955let start: number = new Date().getTime(); 956while (new Date().getTime() - start < 1000) { 957 continue; 958} 959let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo(); 960let tid: number = 0; 961let taskIds: Array<number> = []; 962let priority: number = 0; 963let taskId: number = 0; 964let state: number = 0; 965let duration: number = 0; 966let threadIS = Array.from(taskpoolInfo.threadInfos) 967for(let threadInfo of threadIS) { 968 tid = threadInfo.tid; 969 if (threadInfo.taskIds != undefined && threadInfo.priority != undefined ) 970 { 971 taskIds.length = threadInfo.taskIds.length; 972 priority = threadInfo.priority; 973 } 974 console.info("taskpool---tid is:" + tid + ", taskIds is:" + taskIds + ", priority is:" + priority); 975} 976let taskIS = Array.from(taskpoolInfo.taskInfos) 977for(let taskInfo of taskIS) { 978 taskId = taskInfo.taskId; 979 state = taskInfo.state; 980 if (taskInfo.duration != undefined ) 981 { 982 duration = taskInfo.duration; 983 } 984 console.info("taskpool---taskId is:" + taskId + ", state is:" + state + ", duration is:" + duration); 985} 986``` 987