1# @ohos.taskpool (Using 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).| 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 func(args) { 64 console.log("func: " + args); 65 return args; 66} 67 68let task = new taskpool.Task(func, "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 84Executes a task in the task pool. You must pass in a function and arguments to execute the task, and the task 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 used to execute the task. 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).| 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 func(args) { 116 console.log("func: " + args); 117 return args; 118} 119 120async function taskpoolTest() { 121 let value = await taskpool.execute(func, 100); 122 console.log("taskpool result: " + value); 123} 124 125taskpoolTest(); 126``` 127 128## taskpool.execute 129 130execute(task: Task, priority?: Priority): Promise\<unknown> 131 132Executes a task in the task pool. You must pass in a created task, and the task 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 func(args) { 164 console.log("func: " + args); 165 return args; 166} 167 168async function taskpoolTest() { 169 let task = new taskpool.Task(func, 100); 170 let value = await taskpool.execute(task); 171 console.log("taskpool result: " + value); 172} 173 174taskpoolTest(); 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** 201 202```ts 203@Concurrent 204function func(args) { 205 console.log("func: " + args); 206 return args; 207} 208 209async function taskpoolTest() { 210 let task = new taskpool.Task(func, 100); 211 let value = await taskpool.execute(task); 212 try { 213 taskpool.cancel(task); 214 } catch (e) { 215 console.log("taskpool.cancel occur error:" + e); 216 } 217} 218 219taskpoolTest(); 220``` 221 222## Additional Information 223 224### Sequenceable Data Types 225The following sequenceable data types are supported: All Primitive Type (excluding symbol), Date, String, RegExp, Array, Map, Set, Object, ArrayBuffer, and TypedArray. 226 227### Precautions 228- 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**. 229- 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. 230- 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. 231- The decorator **@Concurrent** can be used only in the .ets file. To create a task in the task pool in the .ts file, use the statement **use concurrent**. 232 233### Using the Task Pool in Simple Mode 234 235**Example 1** 236 237```ts 238// Common functions are supported, and variables passed in by input parameters are also supported. 239@Concurrent 240function func(args) { 241 console.log("func: " + args); 242 return args; 243} 244 245async function taskpoolTest() { 246 // taskpool.execute(task) 247 let task = new taskpool.Task(func, "create task, then execute"); 248 let val1 = await taskpool.execute(task); 249 console.log("taskpool.execute(task) result: " + val1); 250 251 // taskpool.execute(function) 252 let val2 = await taskpool.execute(func, "execute task by func"); 253 console.log("taskpool.execute(function) result: " + val2); 254} 255 256taskpoolTest(); 257``` 258 259**Example 2** 260 261```ts 262// b.ets 263export var c = 2000; 264``` 265```ts 266// Reference an imported variable. 267// a.ets (in the same directory as b.ets) 268import { c } from "./b"; 269 270@Concurrent 271function test(a) { 272 console.log(a); 273 console.log(c); 274 return a; 275} 276 277async function taskpoolTest() { 278 // taskpool.execute(task) 279 let task = new taskpool.Task(test, "create task, then execute"); 280 let val1 = await taskpool.execute(task); 281 console.log("taskpool.execute(task) result: " + val1); 282 283 // taskpool.execute(function) 284 let val2 = await taskpool.execute(test, "execute task by func"); 285 console.log("taskpool.execute(function) result: " + val2); 286} 287 288taskpoolTest(); 289``` 290 291**Example 3** 292 293```ts 294// The async functions are supported. 295@Concurrent 296async function task() { 297 let ret = await Promise.all([ 298 new Promise(resolve => setTimeout(resolve, 1000, "resolved")) 299 ]); 300 return ret; 301} 302 303async function taskpoolTest() { 304 taskpool.execute(task).then((result) => { 305 console.log("TaskPoolTest task result: " + result); 306 }); 307} 308 309taskpoolTest(); 310``` 311 312**Example 4** 313 314```ts 315// Use use concurrent to create a task in the task pool in the .ts file. 316// c.ts 317function test1(n) { 318 "use concurrent" 319 return n; 320} 321export async function taskpoolTest1() { 322 console.log("taskpoolTest1 start"); 323 var task = new taskpool.Task(test1, 100); 324 var result = await taskpool.execute(task); 325 console.log("taskpoolTest1 result:" + result); 326} 327 328async function test2() { 329 "use concurrent" 330 var ret = await Promise.all([ 331 new Promise(resolve => setTimeout(resolve, 1000, "resolved")) 332 ]); 333 return ret; 334} 335export async function taskpoolTest2() { 336 console.log("taskpoolTest2 start"); 337 taskpool.execute(test2).then((result) => { 338 console.log("TaskPoolTest2 result: " + result); 339 }); 340} 341``` 342 343```ts 344/ / a.ets (in the same directory as c.ts) 345import { taskpoolTest1, taskpoolTest2 } from "./c"; 346 347taskpoolTest1(); 348taskpoolTest2(); 349``` 350