DEV Community

SameX
SameX

Posted on

The World of HarmonyOS Programming: Handling I/O-Intensive Tasks and the Asynchronous Lock Mechanism in ArkTS

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.
I/O-intensive tasks refer to those tasks that require a large number of I/O operations such as disk reading and writing, and network communication. The characteristics of I/O-intensive tasks are that they are time-consuming and prone to blocking threads, which may cause the application to freeze.
ArkTS provides an asynchronous lock mechanism to solve the problem of data contention in multi-threaded concurrency and avoid deadlock problems.

Characteristics and Development Strategies of I/O-Intensive Tasks

Characteristics of I/O-Intensive Tasks:

  • Time-consuming: I/O operations usually take a long time to complete, such as reading and writing files, and making network requests.
  • Blocking Threads: I/O operations will block the current thread, preventing the thread from executing other tasks and affecting the response speed of the application.
  • Frequent Occurrence: In many applications, I/O operations occur frequently, such as file reading and writing, database operations, and network communication. Development Strategies:
  • Using Asynchronous Programming Techniques: For example, Promise and async/await can make I/O operations execute asynchronously, avoid blocking threads, and improve the response speed of the application.
  • Using Multi-Threaded Concurrency Techniques: For example, TaskPool and Worker can assign I/O tasks to different threads for execution, improving the efficiency of I/O operations.
  • Using Buffer Techniques: For example, using a caching mechanism can reduce the number of I/O operations and improve the efficiency of I/O operations. ### Usage Scenarios and Advantages of Asynchronous Locks in ArkTS Usage Scenarios:
  • Sharing Data: When multiple concurrent instances need to share the same piece of data, asynchronous locks need to be used to ensure the thread safety of the data and avoid data contention problems.
  • Accessing Resources: When multiple concurrent instances need to access the same resource, asynchronous locks need to be used to ensure the order of resource access and avoid deadlock problems. Advantages:
  • Non-blocking: Asynchronous locks are non-blocking and will not cause deadlock problems.
  • Cross-thread Passing: Asynchronous locks can be passed by reference across concurrent instances, improving development efficiency.
  • Automatic Release: Asynchronous locks will be automatically released after the code execution is completed, avoiding memory leaks. ### Handling to Avoid Deadlock Problems
  • Lock Granularity: The granularity of asynchronous locks must be small enough to avoid multiple concurrent instances holding locks for a long time, which may cause deadlock problems.
  • Lock Release: Asynchronous locks need to be released immediately after the code execution is completed to avoid memory leaks.
  • Lock Order: If multiple locks need to be used, they need to be acquired in a certain order to avoid deadlock problems. ### Example of Concurrent Tasks with Intensive I/O Operations The following is a simple example demonstrating how to use TaskPool to execute concurrent tasks with intensive I/O operations:
import { taskpool } from '@kit.ArkTS';
import { fileIo } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
async function writeFiles(context: common.UIAbilityContext) {
    const filePath1: string = context.filesDir + "/path1.txt";
    const filePath2: string = context.filesDir + "/path2.txt";
    const fileList: Array<string> = [filePath1, filePath2];
    for (let i = 0; i < fileList.length; i++) {
        await fileIo.write(filePathList[i], "Hello World!");
    }
}
async function main() {
    const context = await getApplicationContext();
    await taskpool.execute(writeFiles, context);
}
@Entry
@Component
struct Index {
    @State message: string = 'Hello World';
    build() {
        Column() {
            Text(this.message)
             .fontSize(50)
             .fontWeight(FontWeight.Bold)
             .onClick(async () => {
                    await main();
                })
             .width('100%');
        }
     .height('100%');
    }
}
Enter fullscreen mode Exit fullscreen mode

This code defines a component named Index and displays a text message "Hello World" in the component. Clicking the button will execute the main function, which creates a concurrent task and executes it. The task will intensively write to two files and output the results.

Comparison between Synchronous Locks and Asynchronous Locks

Characteristics Synchronous Locks Asynchronous Locks
Blocking Yes No
Deadlock Problem Possible Impossible
Granularity Can be large Must be small
Release Need to be released manually Automatically released
Cross-thread Passing Not supported Supported

Summary

Through the above introduction, you can understand the handling methods of I/O-intensive tasks in the HarmonyOS system and the asynchronous lock mechanism in ArkTS. Using asynchronous programming techniques and asynchronous lock mechanism can improve the efficiency of I/O operations and avoid deadlock problems. Hope this article can help you master the concurrent programming techniques in the HarmonyOS system and develop better HarmonyOS applications.

Top comments (0)