W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
使用異步并發(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ù)的處理。
- import fs from '@ohos.file.fs';
- // 定義并發(fā)函數(shù),內(nèi)部密集調(diào)用I/O能力
- @Concurrent
- async function concurrentTest(fileList: string[]) {
- // 寫入文件的實(shí)現(xiàn)
- async function write(data, filePath) {
- let file = await fs.open(filePath, fs.OpenMode.READ_WRITE);
- await fs.write(file.fd, data);
- fs.close(file);
- }
- // 循環(huán)寫文件操作
- for (let i = 0; i < fileList.length; i++) {
- write('Hello World!', fileList[i]).then(() => {
- console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`);
- }).catch((err) => {
- console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`)
- return false;
- })
- }
- return true;
- }
- import taskpool from '@ohos.taskpool';
- let filePath1 = ...; // 應(yīng)用文件路徑
- let filePath2 = ...;
- // 使用TaskPool執(zhí)行包含密集I/O的并發(fā)函數(shù)
- // 數(shù)組較大時(shí),I/O密集型任務(wù)任務(wù)分發(fā)也會(huì)搶占主線程,需要使用多線程能力
- taskpool.execute(concurrentTest, [filePath1, filePath2]).then((ret) => {
- // 調(diào)度結(jié)果處理
- console.info(`The result: ${ret}`);
- })
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: