Read the original article:Implementing Multithreaded Concurrency Using TaskPool in ArkTS
Requirement Description
TaskPool is designed to provide a multithreaded runtime environment for applications. It helps reduce overall resource consumption and improve system performance. It also frees you from caring about the lifecycle of thread instances.
Background Knowledge
Multithreaded concurrency refers to the execution of multiple threads simultaneously within a single program, enhancing performance and resource utilization through parallel or alternating task execution.
ArkTS provides two concurrency models, both implemented based on the actor model: TaskPool and Worker.
· Shared memory model uses locks to manage memory access.
· Actor model assigns independent memory to each actor/thread and uses message transfer for interaction.
TaskPool implements the actor model. It manages a task queue and dynamically schedules tasks to worker threads based on load. The number of worker threads grows and shrinks according to the number of incoming tasks.
Implementation Steps
Define a concurrent function with
@Concurrent(must be in.etsfile).Create a
taskpool.Taskobject using this function.Use
taskpool.execute()to run the task.Retrieve the result via
.then()or handle failure via.catch().Optionally use
TaskGroupfor batching.Use
setCloneList()orsetTransferList()for ArrayBuffer parameter control.
Code Snippet / Configuration
Basic Concurrent Function with TaskPool
import { taskpool } from '@kit.ArkTS';
@Concurrent
function add(num1: number, num2: number): number {
return num1 + num2;
}
async function concurrentFunc(): Promise<void> {
try {
const task: taskpool.Task = new taskpool.Task(add, 1, 2);
console.info(`taskpool res is: ${await taskpool.execute(task)}`);
} catch (e) {
console.error(`taskpool execute error is: ${e}}`);
}
}
Using ArrayBuffer and setCloneList
@Concurrent
function printArrayBuffer(buffer: ArrayBuffer) {
return buffer;
}
function testArrayBuffer() {
const buffer = new ArrayBuffer(1);
const group = new taskpool.TaskGroup();
const task = new taskpool.Task(printArrayBuffer, buffer);
group.addTask(task);
task.setCloneList([buffer]);
for (let i = 0; i < 5; i++) {
taskpool.execute(group).then(() => {
console.info('execute group success');
}).catch((e: BusinessError) => {
console.error(`execute group error: ${e.message}`);
})
}
}
@Concurrent Limitations (Closure Violation)
function bar() {}
@Concurrent
function foo() {
bar(); // This violates the closure principle. An error is reported.
}
Test Results
· Producer/Consumer examples run using TaskPool.
· ArrayBuffer clone and transfer tested via setCloneList() and setTransferList().
· Promise-returning concurrent functions are handled.
· TaskPool scaling observed (dynamic worker thread creation and destruction).
Limitations
· Only .ets files support @Concurrent.
· Concurrent functions cannot use closures or call local functions in the same file.
· Thread-unsafe libraries (like UI components) cannot be used.
· AppStorage and unresolved Promises cannot be transferred.
· Max serializable data is 16 MB.
· Functions must complete within 3 minutes (excluding await time).
· TaskPool does not allow selecting specific thread for task execution.
· TaskPool scaling:
o Threads expand if idle thread count < task count.
o Idle threads (30s+) are released periodically unless handling long tasks or in debug state.
Related Documents
- TaskPool-Multithreaded Concurrency-ArkTS Concurrency-ArkTS-Application Framework - HUAWEI Developers
Top comments (0)