A Brief Discussion on Multithreading in HarmonyOS
Today, I'd like to discuss multithreading in HarmonyOS development with you. ArkTS provides two concurrency capabilities, TaskPool and Worker, for developers to choose from. First, let me share my personal understanding: Use TaskPool in scenarios where lightweight and frequent use of multithreading is required. Use Worker when there are tasks with large computational amounts and high resource consumption that need multithreading. 1. Concepts The main function of TaskPool is to provide a multithreading running environment for applications. It enables developers to submit tasks to the task queue in the host thread. The system selects an appropriate worker thread to execute the task and then returns the result to the host thread. There is no need to manage the thread lifecycle. The main function of Worker is also to provide a multithreading running environment for applications. It ensures that the application can be separated from the host thread during execution and run scripts in the background thread for time-consuming operations, avoiding computation-intensive or high-latency tasks from blocking the host thread. When it's no longer needed, it needs to be manually destroyed; otherwise, it will keep consuming memory. 2. Applicable Scenarios Worker: Suitable for tasks that need to run for a long time and are relatively independent, such as processing a large amount of data and performing complex algorithm calculations. Since the Worker creates an independent thread, it can continuously perform complex calculation tasks without affecting the main thread. TaskPool: More suitable for executing multiple short-term tasks, especially those that can be executed in parallel. For example, when an application is starting up and there are tasks for initializing multiple modules simultaneously, using TaskPool can distribute these tasks to different threads for parallel execution, thus improving the application's startup speed. 3. Usage Methods Worker: To create a Worker, you need to specify a script file and write the task logic to be executed in that script file. Communication between the main thread and the Worker thread is carried out through the postMessage method. Here is a simple example: Add the following configuration to the module-level entry/build-profile.json5 configuration file: "buildOption": { "sourceOption": { "workers": [ "./src/main/ets/workers/Worker.ets" ] } } // Create a Worker object in the host thread const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets"); // The host thread sends information to the worker thread workerInstance.postMessage({ data: 'test' }); // The host thread receives information from the worker thread workerInstance.onmessage = (e: MessageEvents): void => { // data: Information sent by the worker thread console.info("main thread data is " + e.data); // Destroy the Worker object workerInstance.terminate(); } // After calling terminate, execute onexit workerInstance.onexit = (code) => { console.log("main thread terminate"); } workerInstance.onerror = (err: ErrorEvent) => { console.log("main error message " + err.message); } // Worker.ets import { worker, MessageEvents, ErrorEvent } from '@kit.ArkTS'; // Create an object in the worker thread for communication with the host thread const workerPort = worker.workerPort // The worker thread receives information from the host thread workerPort.onmessage = (e: MessageEvents): void => { // data: Information sent by the host thread console.info("main thread data is " + e.data); // The worker thread sends information to the host thread workerPort.postMessage('result'); } // Callback when an error occurs in the worker thread workerPort.onerror = (err: ErrorEvent) => { console.log("worker.ets onerror" + err.message); } TaskPool: When using TaskPool, developers only need to define the task function and then submit the task to the TaskPool. The TaskPool will automatically select an appropriate thread to execute the task. Here is an example of using TaskPool: import { taskpool } from '@kit.ArkTS'; @Concurrent function add(num1: number, num2: number): number { return num1 + num2; } async function ConcurrentFunc(): Promise { let task: taskpool.Task = new taskpool.Task(add, 1, 2); console.info("taskpool.execute(task) result: " + await taskpool.execute(task)); } 4. Resource Management Worker: Each Worker creates an independent thread, so it will occupy relatively more system resources. When the Worker task is completed, if it is not manually terminated, it will keep occupying system resources. In the same process, theoretically, a maximum of 64 Workers can be configured (the actual number depends on the remaining memory space). TaskPool: TaskPool manages threads through a thread pool, avoiding the resource overhead caused by frequent crea

Today, I'd like to discuss multithreading in HarmonyOS development with you. ArkTS provides two concurrency capabilities, TaskPool and Worker, for developers to choose from.
First, let me share my personal understanding: Use TaskPool in scenarios where lightweight and frequent use of multithreading is required. Use Worker when there are tasks with large computational amounts and high resource consumption that need multithreading.
1. Concepts
- The main function of
TaskPool
is to provide a multithreading running environment for applications. It enables developers to submit tasks to the task queue in the host thread. The system selects an appropriate worker thread to execute the task and then returns the result to the host thread. There is no need to manage the thread lifecycle.
- The main function of
Worker
is also to provide a multithreading running environment for applications. It ensures that the application can be separated from the host thread during execution and run scripts in the background thread for time-consuming operations, avoiding computation-intensive or high-latency tasks from blocking the host thread. When it's no longer needed, it needs to be manually destroyed; otherwise, it will keep consuming memory.
2. Applicable Scenarios
Worker: Suitable for tasks that need to run for a long time and are relatively independent, such as processing a large amount of data and performing complex algorithm calculations. Since the
Worker
creates an independent thread, it can continuously perform complex calculation tasks without affecting the main thread.TaskPool: More suitable for executing multiple short-term tasks, especially those that can be executed in parallel. For example, when an application is starting up and there are tasks for initializing multiple modules simultaneously, using
TaskPool
can distribute these tasks to different threads for parallel execution, thus improving the application's startup speed.
3. Usage Methods
-
Worker: To create a
Worker
, you need to specify a script file and write the task logic to be executed in that script file. Communication between the main thread and theWorker
thread is carried out through thepostMessage
method. Here is a simple example:
Add the following configuration to the module-level entry/build-profile.json5 configuration file:
"buildOption": {
"sourceOption": {
"workers": [
"./src/main/ets/workers/Worker.ets"
]
}
}
// Create a Worker object in the host thread
const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
// The host thread sends information to the worker thread
workerInstance.postMessage({ data: 'test' });
// The host thread receives information from the worker thread
workerInstance.onmessage = (e: MessageEvents): void => {
// data: Information sent by the worker thread
console.info("main thread data is " + e.data);
// Destroy the Worker object
workerInstance.terminate();
}
// After calling terminate, execute onexit
workerInstance.onexit = (code) => {
console.log("main thread terminate");
}
workerInstance.onerror = (err: ErrorEvent) => {
console.log("main error message " + err.message);
}
// Worker.ets
import { worker, MessageEvents, ErrorEvent } from '@kit.ArkTS';
// Create an object in the worker thread for communication with the host thread
const workerPort = worker.workerPort
// The worker thread receives information from the host thread
workerPort.onmessage = (e: MessageEvents): void => {
// data: Information sent by the host thread
console.info("main thread data is " + e.data);
// The worker thread sends information to the host thread
workerPort.postMessage('result');
}
// Callback when an error occurs in the worker thread
workerPort.onerror = (err: ErrorEvent) => {
console.log("worker.ets onerror" + err.message);
}
-
TaskPool: When using
TaskPool
, developers only need to define the task function and then submit the task to theTaskPool
. TheTaskPool
will automatically select an appropriate thread to execute the task. Here is an example of usingTaskPool
:
import { taskpool } from '@kit.ArkTS';
@Concurrent
function add(num1: number, num2: number): number {
return num1 + num2;
}
async function ConcurrentFunc(): Promise<void> {
let task: taskpool.Task = new taskpool.Task(add, 1, 2);
console.info("taskpool.execute(task) result: " + await taskpool.execute(task));
}
4. Resource Management
Worker: Each
Worker
creates an independent thread, so it will occupy relatively more system resources. When theWorker
task is completed, if it is not manually terminated, it will keep occupying system resources. In the same process, theoretically, a maximum of 64Workers
can be configured (the actual number depends on the remaining memory space).TaskPool:
TaskPool
manages threads through a thread pool, avoiding the resource overhead caused by frequent creation and destruction of threads. The threads in the thread pool can be reused by multiple tasks, thus improving resource utilization. However, theTaskPool
can only execute tasks for a maximum of 3 minutes (usually this time is sufficient because this duration does not include the time-consuming operation of asynchronous waiting).
Summary
Worker
runs the specified script by creating an independent thread, which is suitable for long-term and independent tasks. It requires manual management of thread resources and communicates through messages. TaskPool
, as a thread pool management tool, automatically manages the creation, reuse, and destruction of threads, supports multiple task types, and is suitable for multiple short-term parallel tasks.
The version used in this article and code is HarmonyOS 5.0.1 Release SDK.