• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# I/O Intensive Task Development
2
3
4Asynchronous concurrency can solve the problem of a single blocking I/O operation. In the case of I/O intensive tasks, the execution of other tasks in the thread is still blocked. To resolve this issue, multithread concurrency is introduced.
5
6
7The performance focus of I/O intensive tasks is not the CPU processing capability, but the speed and efficiency of I/O operations, since such a task usually requires frequent operations such as disk read/write and network communication. The following uses frequent read/write operations on a system file to simulate concurrency processing of I/O intensive tasks.
8
9
101. Define a concurrency function that internally calls I/O capabilities intensively.
11
12   ```ts
13   import fs from '@ohos.file.fs';
14
15   // Define a concurrency function that internally calls I/O capabilities intensively.
16   @Concurrent
17   async function concurrentTest(fileList: string[]) {
18     // Implement file writing.
19     async function write(data, filePath) {
20       let file = await fs.open(filePath, fs.OpenMode.READ_WRITE);
21       await fs.write(file.fd, data);
22       fs.close(file);
23     }
24     // Write the file cyclically.
25     for (let i = 0; i < fileList.length; i++) {
26       write('Hello World!', fileList[i]).then(() => {
27         console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`);
28       }).catch((err) => {
29         console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`)
30         return false;
31       })
32     }
33     return true;
34   }
35   ```
36
372. Use **TaskPool** to execute the concurrency function that contains the intensive I/O operations. Specifically, call [execute()](../reference/apis/js-apis-taskpool.md#taskpoolexecute) to execute the tasks and process the scheduling result in a callback. For details about how to obtain **filePath1** and **filePath2** in the example, see [Obtaining Application File Paths](../application-models/application-context-stage.md#obtaining-application-file-paths).
38
39   ```ts
40   import taskpool from '@ohos.taskpool';
41
42   let filePath1 =...; // Application file path
43   let filePath2 = ...;
44
45   // Use TaskPool to execute the concurrency function that contains the intensive I/O operations.
46   // In the case of a large array, the distribution of I/O intensive tasks also preempts the main thread. Therefore, multiple threads are required.
47   taskpool.execute(concurrentTest, [filePath1, filePath2]).then((ret) => {
48     // Process the scheduling result.
49     console.info(`The result: ${ret}`);
50   })
51   ```
52