I/O密集型任務(wù)開發(fā)指導(dǎo)

2024-02-16 13:45 更新

使用異步并發(fā)可以解決單次I/O任務(wù)阻塞的問題,但是如果遇到I/O密集型任務(wù),同樣會(huì)阻塞線程中其它任務(wù)的執(zhí)行,這時(shí)需要使用多線程并發(fā)能力來進(jìn)行解決。

I/O密集型任務(wù)的性能重點(diǎn)通常不在于CPU的處理能力,而在于I/O操作的速度和效率。這種任務(wù)通常需要頻繁地進(jìn)行磁盤讀寫、網(wǎng)絡(luò)通信等操作。此處以頻繁讀寫系統(tǒng)文件來模擬I/O密集型并發(fā)任務(wù)的處理。

  1. 定義并發(fā)函數(shù),內(nèi)部密集調(diào)用I/O能力。

    1. import fs from '@ohos.file.fs';
    2. // 定義并發(fā)函數(shù),內(nèi)部密集調(diào)用I/O能力
    3. @Concurrent
    4. async function concurrentTest(fileList: string[]) {
    5. // 寫入文件的實(shí)現(xiàn)
    6. async function write(data, filePath) {
    7. let file = await fs.open(filePath, fs.OpenMode.READ_WRITE);
    8. await fs.write(file.fd, data);
    9. fs.close(file);
    10. }
    11. // 循環(huán)寫文件操作
    12. for (let i = 0; i < fileList.length; i++) {
    13. write('Hello World!', fileList[i]).then(() => {
    14. console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`);
    15. }).catch((err) => {
    16. console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`)
    17. return false;
    18. })
    19. }
    20. return true;
    21. }

  2. 使用TaskPool執(zhí)行包含密集I/O的并發(fā)函數(shù):通過調(diào)用execute()方法執(zhí)行任務(wù),并在回調(diào)中進(jìn)行調(diào)度結(jié)果處理。示例中的filePath1和filePath2的獲取方式請參見獲取應(yīng)用文件路徑。

    1. import taskpool from '@ohos.taskpool';
    2. let filePath1 = ...; // 應(yīng)用文件路徑
    3. let filePath2 = ...;
    4. // 使用TaskPool執(zhí)行包含密集I/O的并發(fā)函數(shù)
    5. // 數(shù)組較大時(shí),I/O密集型任務(wù)任務(wù)分發(fā)也會(huì)搶占主線程,需要使用多線程能力
    6. taskpool.execute(concurrentTest, [filePath1, filePath2]).then((ret) => {
    7. // 調(diào)度結(jié)果處理
    8. console.info(`The result: ${ret}`);
    9. })
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號