• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# TaskPool Introduction
2
3TaskPool provides a multithreaded environment for applications. It helps reduce resource consumption and improve system performance. It also frees you from caring about the lifecycle of thread instances. For details about the TaskPool APIs and their usage, see [@ohos.taskpool (Starting the Task Pool)](../reference/apis-arkts/js-apis-taskpool.md).
4
5
6## TaskPool Operating Mechanism
7
8**Figure 1** TaskPool operating mechanism
9
10![TaskPool](figures/taskpool.png)
11
12With TaskPool, you can encapsulate tasks in the main thread and throw the tasks to the task queue. The system selects proper worker threads to distribute and execute the tasks, and then returns the result to the main thread. TaskPool provides APIs to execute and cancel tasks, and set the task priority. It minimizes system resource usage through unified thread management, dynamic scheduling, and load balancing. By default, the system starts a worker thread and increases the thread quantity as the number of tasks increases. The maximum number of worker threads that can be created depends on the number of physical cores of the device. The actual number is managed internally to ensure optimal scheduling and execution efficiency. If no task is distributed for a long period of time, the system reduces the number of worker threads.
13
14
15## Precautions for TaskPool
16
17- A task function must be decorated with [\@Concurrent](arkts-concurrent.md) and can be used only in .ets files.
18
19- Since API version 11, when a function that implements a task needs to use a class method, the class must be decorated with [\@Sendable](arkts-sendable.md#sendable-decorator-declaring-and-verifying-a-sendable-class) and used only in .ets files.
20
21- A task function in the TaskPool worker thread must finish the execution within 3 minutes (excluding the time used for Promise or async/await asynchronous call, for example, the duration of I/O tasks such as network download and file read/write). Otherwise, it forcibly exits.
22
23- Input parameter types in a task function must be those supported by serialization. For details, see [Serialization Types Supported by TaskPool and Worker](serialization-support-types.md).
24
25- Parameters of the ArrayBuffer type are transferred in TaskPool by default. You can set the transfer list by calling [setTransferList()](../reference/apis-arkts/js-apis-taskpool.md#settransferlist10).
26
27- Context objects vary in different threads. Therefore, the TaskPool worker thread can use only a thread-safe library, but not a non-thread-safe library (for example, UI-related non-thread-safe library). For details, see [Precautions for Multithread Safe](multi-thread-safety.md).
28
29- A maximum of 16 MB data can be serialized.
30- Among all the values of [Priority](../reference/apis-arkts/js-apis-taskpool.md#priority), **IDLE** is used to mark time-consuming tasks (such as data synchronization and backup) that need to run in the background and has the lowest priority. Tasks marked with **IDLE** are executed only when all threads are idle and occupy only one thread for execution.
31
32- A promise object cannot be passed across threads and cannot be used as the return value of a concurrent function.
33
34```ts
35// Positive example:
36@Concurrent
37async function asyncFunc(val1:number, val2:number): Promise<number> {
38  let ret: number = await new Promise((resolve, reject) => {
39    let value = val1 + val2;
40    resolve(value);
41  });
42  return ret; // Supported. A promise object is returned.
43}
44
45function taskpoolExecute() {
46  taskpool.execute(asyncFunc, 10, 20).then((result: Object) => {
47    console.info("taskPoolTest task result: " + result);
48  }).catch((err: string) => {
49    console.error("taskPoolTest test occur error: " + err);
50  });
51}
52taskpoolExecute()
53```
54
55<!--code_no_check-->
56```ts
57// Negative example 1:
58@Concurrent
59async function asyncFunc(val1:number, val2:number): Promise<number> {
60  let ret: number = await new Promise((resolve, reject) => {
61    let value = val1 + val2;
62    resolve(value);
63  });
64  return Promise.resolve(ret); // Not supported. Promise.resolve is a promise object in pending state. It cannot be used as a return value.
65}
66
67// Negative example 2:
68@Concurrent
69async function asyncFunc(val1:number, val2:number): Promise<number> {
70  // Not supported. The status is pending. It cannot be used as a return value.
71  return new Promise((resolve, reject) => {
72    setTimeout(() => {
73      let value = val1 + val2;
74      resolve(value);
75    }, 2000);
76  });
77}
78
79function taskpoolExecute() {
80  taskpool.execute(asyncFunc, 10, 20).then((result: Object) => {
81    console.info("taskPoolTest task result: " + result);
82  }).catch((err: string) => {
83    console.error("taskPoolTest test occur error: " + err);
84  });
85}
86taskpoolExecute()
87```
88