This article aims to deeply explore the technical details of the Huawei HarmonyOS Next system (up to API 12 as of now), and is summarized based on actual development practices. It mainly serves as a vehicle for technical sharing and communication. Mistakes and omissions are inevitable. Colleagues are welcome to put forward valuable opinions and questions so that we can make progress together. This article is original content, and any form of reprint must indicate the source and the original author.
Concurrent programming refers to the ability to handle multiple tasks within the same period of time. Concurrent programming can improve the response speed and efficiency of an application and prevent time-consuming tasks from blocking the main thread, which may cause the application to freeze.
The HarmonyOS system provides multiple concurrent models, among which TaskPool and Worker are two commonly used concurrent capabilities.
TaskPool: TaskPool is a multi-threaded running environment that provides functions such as task execution, cancellation, and priority setting. TaskPool is suitable for independent tasks, such as computationally intensive tasks and I/O intensive tasks.
Worker: Worker is a long-running background thread that supports message passing between the hosting main thread. Worker is suitable for long-running tasks, such as background data processing and model training.The Purpose and Usage of the @Concurrent Decorator
In the HarmonyOS system, the @Concurrent decorator is used to declare and validate concurrent functions. Starting from API version 9, the use of the @Concurrent decorator to declare and validate concurrent functions is supported.
Decorator Usage:
@Concurrent
function myConcurrentFunction() {
// Code of the concurrent function
}
Decorator Parameters: None.
Usage Scenarios: It is only supported to be used in projects of the Stage model. It is only supported to be used in.ets files.
Types of Decorated Functions: It is allowed to annotate async functions or ordinary functions. It is prohibited to annotate generator functions, arrow functions, or methods. Class member functions or anonymous functions are not supported.
Types of Variables within the Decorated Function: Local variables, input parameters, and variables introduced through import are allowed. Closure variables are prohibited.
Types of Return Values within the Decorated Function: Please refer to the supported serialization types for the supported types.
Declaration and Validation of Concurrent Functions
Concurrent functions refer to functions that can be executed in the TaskPool. Declaring concurrent functions requires using the @Concurrent decorator for decoration and performing necessary validations.
Example:
import { taskpool } from '@kit.ArkTS';
@Concurrent
function add(num1: number, num2: number): number {
return num1 + num2;
}
Precautions for Concurrent Functions:
- Concurrent functions must be decorated with the @Concurrent decorator.
- The types of input parameters and return values of concurrent functions must support serialization.
- Closure variables are not allowed to be used within concurrent functions.
- The execution time of concurrent functions cannot exceed 3 minutes. ### Comparison between the Actor Concurrent Model and the Memory Sharing Model Actor Concurrent Model:
- Each Actor has an independent memory space.
- Actors communicate with each other through a message passing mechanism.
- The Actor concurrent model avoids memory contention issues. Memory Sharing Model:
- Multiple threads share the same memory space.
- Threads need to acquire locks when accessing memory.
- The memory sharing model is prone to data contention issues. Comparison:
- The Actor concurrent model is more suitable for concurrent programming because it avoids memory contention issues.
- The memory sharing model is more suitable for scenarios of shared memory, such as multi-threaded calculations. ### A Basic Example of Executing Concurrent Functions in TaskPool The following is a simple example demonstrating how to execute a concurrent function in TaskPool:
import { taskpool } from '@kit.ArkTS';
@Concurrent
function add(num1: number, num2: number): number {
return num1 + num2;
}
async function concurrentFunc() {
try {
let 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);
}
}
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
concurrentFunc();
})
.width('100%');
}
}
.height('100%');
}
}
This code defines a component named Index
and displays a text message "Hello World" in the component. Clicking the button will execute the concurrentFunc
function, which creates a concurrent task and executes it. After the task is completed, the result will be output on the console.
Summary
Through the above introduction, you can understand the concurrent models in the HarmonyOS system and the usage method of the @Concurrent decorator. Using concurrent programming can effectively improve the response speed and efficiency of an application and prevent time-consuming tasks from blocking the main thread. Hope this article can help you master the concurrent programming techniques in the HarmonyOS system and develop better HarmonyOS applications.
Top comments (0)