提交 83225b3d 编写于 作者: B buzhuyu

fixed 7eb735b5 from https://gitee.com/buzhuyu/docs/pulls/22769

modify taskpool and arkutils adapt to arkts
Signed-off-by: Nbuzhuyu <buzhuyu@huawei.com>
上级 a244185a
...@@ -17,16 +17,16 @@ Promise有三种状态:pending(进行中)、fulfilled(已完成)和rej ...@@ -17,16 +17,16 @@ Promise有三种状态:pending(进行中)、fulfilled(已完成)和rej
```js ```js
const promise = new Promise((resolve, reject) => { const promise: Promise<number> = new Promise((resolve: Function, reject: Function) => {
setTimeout(() => { setTimeout(() => {
const randomNumber = Math.random(); const randomNumber: number = Math.random();
if (randomNumber > 0.5) { if (randomNumber > 0.5) {
resolve(randomNumber); resolve(randomNumber);
} else { } else {
reject(new Error('Random number is too small')); reject(new Error('Random number is too small'));
} }
}, 1000); }, 1000);
}); }
``` ```
上述代码中,setTimeout函数模拟了一个异步操作,并在1秒钟后随机生成一个数字。如果随机数大于0.5,则执行resolve回调函数并将随机数作为参数传递;否则执行reject回调函数并传递一个错误对象作为参数。 上述代码中,setTimeout函数模拟了一个异步操作,并在1秒钟后随机生成一个数字。如果随机数大于0.5,则执行resolve回调函数并将随机数作为参数传递;否则执行reject回调函数并传递一个错误对象作为参数。
...@@ -55,13 +55,13 @@ async函数是一个返回Promise对象的函数,用于表示一个异步操 ...@@ -55,13 +55,13 @@ async函数是一个返回Promise对象的函数,用于表示一个异步操
```js ```js
async function myAsyncFunction() { async function myAsyncFunction(): Promise<void> {
const result = await new Promise((resolve) => { const result: string = await new Promise((resolve: Function) => {
setTimeout(() => { setTimeout(() => {
resolve('Hello, world!'); resolve('Hello, world!');
}, 3000); }, 3000);
}); });
console.info(String(result)); // 输出: Hello, world! console.info(result); // 输出: Hello, world!
} }
myAsyncFunction(); myAsyncFunction();
...@@ -73,9 +73,9 @@ myAsyncFunction(); ...@@ -73,9 +73,9 @@ myAsyncFunction();
```js ```js
async function myAsyncFunction() { async function myAsyncFunction(): Promise<void> {
try { try {
const result = await new Promise((resolve) => { const result: string = await new Promise((resolve: Function) => {
resolve('Hello, world!'); resolve('Hello, world!');
}); });
} catch (e) { } catch (e) {
......
...@@ -24,19 +24,19 @@ CPU密集型任务是指需要占用系统资源处理大量计算能力的任 ...@@ -24,19 +24,19 @@ CPU密集型任务是指需要占用系统资源处理大量计算能力的任
import taskpool from '@ohos.taskpool'; import taskpool from '@ohos.taskpool';
@Concurrent @Concurrent
function imageProcessing(dataSlice: ArrayBuffer) { function imageProcessing(dataSlice: ArrayBuffer): ArrayBuffer {
// 步骤1: 具体的图像处理操作及其他耗时操作 // 步骤1: 具体的图像处理操作及其他耗时操作
return dataSlice; return dataSlice;
} }
function histogramStatistic(pixelBuffer: ArrayBuffer) { function histogramStatistic(pixelBuffer: ArrayBuffer): void {
// 步骤2: 分成三段并发调度 // 步骤2: 分成三段并发调度
let number = pixelBuffer.byteLength / 3; let number: number = pixelBuffer.byteLength / 3;
let buffer1 = pixelBuffer.slice(0, number); let buffer1: ArrayBuffer = pixelBuffer.slice(0, number);
let buffer2 = pixelBuffer.slice(number, number * 2); let buffer2: ArrayBuffer = pixelBuffer.slice(number, number * 2);
let buffer3 = pixelBuffer.slice(number * 2); let buffer3: ArrayBuffer = pixelBuffer.slice(number * 2);
let group = new taskpool.TaskGroup(); let group: taskpool.TaskGroup = new taskpool.TaskGroup();
group.addTask(imageProcessing, buffer1); group.addTask(imageProcessing, buffer1);
group.addTask(imageProcessing, buffer2); group.addTask(imageProcessing, buffer2);
group.addTask(imageProcessing, buffer3); group.addTask(imageProcessing, buffer3);
...@@ -79,30 +79,28 @@ struct Index { ...@@ -79,30 +79,28 @@ struct Index {
![newWorker](figures/newWorker.png) ![newWorker](figures/newWorker.png)
2. 在主线程中通过调用ThreadWorker的[constructor()](../reference/apis/js-apis-worker.md#constructor9)方法创建Worker对象,当前线程为宿主线程。 2. 在主线程中通过调用ThreadWorker的[constructor()](../reference/apis/js-apis-worker.md#constructor9)方法创建Worker对象,当前线程为宿主线程。
```js ```js
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const workerInstance = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); const workerInstance: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts');
``` ```
3. 在宿主线程中通过调用[onmessage()](../reference/apis/js-apis-worker.md#onmessage9)方法接收Worker线程发送过来的消息,并通过调用[postMessage()](../reference/apis/js-apis-worker.md#postmessage9)方法向Worker线程发送消息。 3. 在宿主线程中通过调用[onmessage()](../reference/apis/js-apis-worker.md#onmessage9)方法接收Worker线程发送过来的消息,并通过调用[postMessage()](../reference/apis/js-apis-worker.md#postmessage9)方法向Worker线程发送消息。
例如向Worker线程发送训练和预测的消息,同时接收Worker线程发送回来的消息。 例如向Worker线程发送训练和预测的消息,同时接收Worker线程发送回来的消息。
```js ```js
// 接收Worker子线程的结果 // 接收Worker子线程的结果
workerInstance.onmessage = function(e) { workerInstance.onmessage = function(e) {
// data:主线程发送的信息
let data = e.data;
console.info('MyWorker.ts onmessage'); console.info('MyWorker.ts onmessage');
// 在Worker线程中进行耗时操作 // 在Worker线程中进行耗时操作
} }
workerInstance.onerror = function (d) { workerInstance.onerror = function (d) {
// 接收Worker子线程的错误信息 // 接收Worker子线程的错误信息
} }
// 向Worker子线程发送训练消息 // 向Worker子线程发送训练消息
workerInstance.postMessage({ 'type': 0 }); workerInstance.postMessage({ 'type': 0 });
// 向Worker子线程发送预测消息 // 向Worker子线程发送预测消息
...@@ -110,40 +108,39 @@ struct Index { ...@@ -110,40 +108,39 @@ struct Index {
``` ```
4. 在MyWorker.ts文件中绑定Worker对象,当前线程为Worker线程。 4. 在MyWorker.ts文件中绑定Worker对象,当前线程为Worker线程。
```js ```js
import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker'; import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker';
let workerPort: ThreadWorkerGlobalScope = worker.workerPort; let workerPort: ThreadWorkerGlobalScope = worker.workerPort;
``` ```
5. 在Worker线程中通过调用[onmessage()](../reference/apis/js-apis-worker.md#onmessage9-1)方法接收宿主线程发送的消息内容,并通过调用[postMessage()](../reference/apis/js-apis-worker.md#postmessage9-2)方法向宿主线程发送消息。 5. 在Worker线程中通过调用[onmessage()](../reference/apis/js-apis-worker.md#onmessage9-1)方法接收宿主线程发送的消息内容,并通过调用[postMessage()](../reference/apis/js-apis-worker.md#postmessage9-2)方法向宿主线程发送消息。
例如在Worker线程中定义预测模型及其训练过程,同时与主线程进行信息交互。 例如在Worker线程中定义预测模型及其训练过程,同时与主线程进行信息交互。
```js ```js
import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker'; import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker';
let workerPort: ThreadWorkerGlobalScope = worker.workerPort; let workerPort: ThreadWorkerGlobalScope = worker.workerPort;
// 定义训练模型及结果 // 定义训练模型及结果
let result; let result;
// 定义预测函数 // 定义预测函数
function predict(x) { function predict(x) {
return result[x]; return result[x];
} }
// 定义优化器训练过程 // 定义优化器训练过程
function optimize() { function optimize() {
result = {}; result = {};
} }
// Worker线程的onmessage逻辑 // Worker线程的onmessage逻辑
workerPort.onmessage = function (e: MessageEvents) { workerPort.onmessage = (e: MessageEvents): void => {
let data = e.data
// 根据传输的数据的type选择进行操作 // 根据传输的数据的type选择进行操作
switch (data.type) { switch (e.data.type) {
case 0: case 0:
// 进行训练 // 进行训练
optimize(); optimize();
...@@ -152,7 +149,7 @@ struct Index { ...@@ -152,7 +149,7 @@ struct Index {
break; break;
case 1: case 1:
// 执行预测 // 执行预测
const output = predict(data.value); const output = predict(e.data.value);
// 发送主线程预测的结果 // 发送主线程预测的结果
workerPort.postMessage({ type: 'predict', value: output }); workerPort.postMessage({ type: 'predict', value: output });
break; break;
...@@ -166,7 +163,7 @@ struct Index { ...@@ -166,7 +163,7 @@ struct Index {
6. 在Worker线程中完成任务之后,执行Worker线程销毁操作。销毁线程的方式主要有两种:根据需要可以在宿主线程中对Worker线程进行销毁;也可以在Worker线程中主动销毁Worker线程。 6. 在Worker线程中完成任务之后,执行Worker线程销毁操作。销毁线程的方式主要有两种:根据需要可以在宿主线程中对Worker线程进行销毁;也可以在Worker线程中主动销毁Worker线程。
在宿主线程中通过调用[onexit()](../reference/apis/js-apis-worker.md#onexit9)方法定义Worker线程销毁后的处理逻辑。 在宿主线程中通过调用[onexit()](../reference/apis/js-apis-worker.md#onexit9)方法定义Worker线程销毁后的处理逻辑。
```js ```js
// Worker线程销毁后,执行onexit回调方法 // Worker线程销毁后,执行onexit回调方法
workerInstance.onexit = function() { workerInstance.onexit = function() {
...@@ -182,7 +179,7 @@ struct Index { ...@@ -182,7 +179,7 @@ struct Index {
``` ```
方式二:在Worker线程中通过调用[close()](../reference/apis/js-apis-worker.md#close9)方法主动销毁Worker线程,并终止Worker接收消息。 方式二:在Worker线程中通过调用[close()](../reference/apis/js-apis-worker.md#close9)方法主动销毁Worker线程,并终止Worker接收消息。
```js ```js
// 销毁线程 // 销毁线程
workerPort.close(); workerPort.close();
......
...@@ -8,43 +8,45 @@ I/O密集型任务的性能重点通常不在于CPU的处理能力,而在于I/ ...@@ -8,43 +8,45 @@ I/O密集型任务的性能重点通常不在于CPU的处理能力,而在于I/
1. 定义并发函数,内部密集调用I/O能力。 1. 定义并发函数,内部密集调用I/O能力。
```ts ```ts
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
// 定义并发函数,内部密集调用I/O能力
@Concurrent // 定义并发函数,内部密集调用I/O能力
async function concurrentTest(fileList: string[]) { // 写入文件的实现
// 写入文件的实现 async function write(data: string, filePath: string): Promise<void> {
async function write(data, filePath) { let file: fs.File = await fs.open(filePath, fs.OpenMode.READ_WRITE);
let file = await fs.open(filePath, fs.OpenMode.READ_WRITE); await fs.write(file.fd, data);
await fs.write(file.fd, data); fs.close(file);
fs.close(file); }
}
// 循环写文件操作 @Concurrent
for (let i = 0; i < fileList.length; i++) { async function concurrentTest(fileList: string[]): Promise<boolean> {
write('Hello World!', fileList[i]).then(() => { // 循环写文件操作
console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`); for (let i: number = 0; i < fileList.length; i++) {
}).catch((err) => { write('Hello World!', fileList[i]).then(() => {
console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`) console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`);
return false; }).catch((err: BusinessError) => {
}) console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`)
} return false;
return true; })
} }
return true;
}
``` ```
2. 使用TaskPool执行包含密集I/O的并发函数:通过调用[execute()](../reference/apis/js-apis-taskpool.md#taskpoolexecute)方法执行任务,并在回调中进行调度结果处理。示例中的filePath1和filePath2的获取方式请参见[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径) 2. 使用TaskPool执行包含密集I/O的并发函数:通过调用[execute()](../reference/apis/js-apis-taskpool.md#taskpoolexecute)方法执行任务,并在回调中进行调度结果处理。示例中的filePath1和filePath2的获取方式请参见[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径)
```ts ```ts
import taskpool from '@ohos.taskpool'; import taskpool from '@ohos.taskpool';
let filePath1 = ...; // 应用文件路径 let filePath1: string = ...; // 应用文件路径
let filePath2 = ...; let filePath2: string = ...;
// 使用TaskPool执行包含密集I/O的并发函数 // 使用TaskPool执行包含密集I/O的并发函数
// 数组较大时,I/O密集型任务任务分发也会抢占主线程,需要使用多线程能力 // 数组较大时,I/O密集型任务任务分发也会抢占主线程,需要使用多线程能力
taskpool.execute(concurrentTest, [filePath1, filePath2]).then((ret) => { taskpool.execute(concurrentTest, [filePath1, filePath2]).then(() => {
// 调度结果处理 // 调度结果处理
console.info(`The result: ${ret}`); console.info(`The result: ${ret}`);
}) })
......
...@@ -202,52 +202,59 @@ Stack进行增、删、改、查操作的常用API如下: ...@@ -202,52 +202,59 @@ Stack进行增、删、改、查操作的常用API如下:
// ArrayList // ArrayList
import ArrayList from '@ohos.util.ArrayList'; // 导入ArrayList模块 import ArrayList from '@ohos.util.ArrayList'; // 导入ArrayList模块
let arrayList = new ArrayList(); let arrayList1: ArrayList<string> = new ArrayList();
arrayList.add('a'); arrayList1.add('a');
arrayList.add(1); // 增加元素 let arrayList2: ArrayList<number> = new ArrayList();
console.info(`result: ${arrayList[0]}`); // 访问元素 arrayList2.add(1); // 增加元素
arrayList[0] = 'one'; // 修改元素 console.info(`result: ${arrayList2[0]}`); // 访问元素
console.info(`result: ${arrayList[0]}`); arrayList1[0] = 'one'; // 修改元素
console.info(`result: ${arrayList1[0]}`);
// Vector // Vector
import Vector from '@ohos.util.Vector'; // 导入Vector模块 import Vector from '@ohos.util.Vector'; // 导入Vector模块
let vector = new Vector(); let vector1: Vector<string> = new Vector();
vector.add('a'); vector1.add('a');
let vector2: Vector<Array<number>> = new Vector();
let b1 = [1, 2, 3]; let b1 = [1, 2, 3];
vector.add(b1); vector2.add(b1);
vector.add(false); // 增加元素 let vector3: Vector<boolean> = new Vector();
console.info(`result: ${vector[0]}`); // 访问元素 vector3.add(false); // 增加元素
console.info(`result: ${vector.getFirstElement()}`); // 访问元素 console.info(`result: ${vector1[0]}`); // 访问元素
console.info(`result: ${vector2.getFirstElement()}`); // 访问元素
// Deque // Deque
import Deque from '@ohos.util.Deque'; // 导入Deque模块 import Deque from '@ohos.util.Deque'; // 导入Deque模块
let deque = new Deque; let deque1: Deque<string> = new Deque;
deque.insertFront('a'); deque1.insertFront('a');
deque.insertFront(1); // 增加元素 let deque2: Deque<number> = new Deque;
console.info(`result: ${deque[0]}`); // 访问元素 deque2.insertFront(1); // 增加元素
deque[0] = 'one'; // 修改元素 console.info(`result: ${deque1[0]}`); // 访问元素
console.info(`result: ${deque[0]}`); deque1[0] = 'one'; // 修改元素
console.info(`result: ${deque2[0]}`);
// Stack // Stack
import Stack from '@ohos.util.Stack'; // 导入Stack模块 import Stack from '@ohos.util.Stack'; // 导入Stack模块
let stack = new Stack(); let stack1: Stack<string> = new Stack();
stack.push('a'); stack1.push('a');
stack.push(1); // 增加元素 let stack2: Stack<number> = new Stack();
console.info(`result: ${stack[0]}`); // 访问元素 stack2.push(1); // 增加元素
stack.pop(); // 弹出元素 console.info(`result: ${stack1[0]}`); // 访问元素
console.info(`result: ${stack.length}`); stack2.pop(); // 弹出元素
console.info(`result: ${stack2.length}`);
// List // List
import List from '@ohos.util.List'; // 导入List模块 import List from '@ohos.util.List'; // 导入List模块
let list = new List; let list1: List<string> = new List;
list.add('a'); list1.add('a');
list.add(1); let list2: List<number> = new List;
list2.add(1);
let list3: List<Array<number>> = new List;
let b2 = [1, 2, 3]; let b2 = [1, 2, 3];
list.add(b2); // 增加元素 list3.add(b2); // 增加元素
console.info(`result: ${list[0]}`); // 访问元素 console.info(`result: ${list1[0]}`); // 访问元素
console.info(`result: ${list.get(0)}`); // 访问元素 console.info(`result: ${list3.get(0)}`); // 访问元素
``` ```
...@@ -29,7 +29,7 @@ Actor并发模型作为基于消息通信并发模型的典型代表,不需要 ...@@ -29,7 +29,7 @@ Actor并发模型作为基于消息通信并发模型的典型代表,不需要
```js ```js
// 定义可转移对象 // 定义可转移对象
let buffer = new ArrayBuffer(100); let buffer: ArrayBuffer = new ArrayBuffer(100);
``` ```
...@@ -44,7 +44,7 @@ SharedArrayBuffer对象存储的数据在同时被修改时,需要通过原子 ...@@ -44,7 +44,7 @@ SharedArrayBuffer对象存储的数据在同时被修改时,需要通过原子
```js ```js
// 定义可共享对象,可以使用Atomics进行操作 // 定义可共享对象,可以使用Atomics进行操作
let sharedBuffer = new SharedArrayBuffer(1024); let sharedBuffer: SharedArrayBuffer = new SharedArrayBuffer(1024);
``` ```
### Native绑定对象 ### Native绑定对象
......
...@@ -216,16 +216,17 @@ PlainArray进行增、删、改、查操作的常用API如下: ...@@ -216,16 +216,17 @@ PlainArray进行增、删、改、查操作的常用API如下:
// HashMap // HashMap
import HashMap from '@ohos.util.HashMap'; // 导入HashMap模块 import HashMap from '@ohos.util.HashMap'; // 导入HashMap模块
let hashMap = new HashMap(); let hashMap1: HashMap<string, number> = new HashMap();
hashMap.set('a', 123); hashMap1.set('a', 123);
hashMap.set(4, 123); // 增加元素 let hashMap2: HashMap<number, number> = new HashMap();
console.info(`result: ${hashMap.hasKey(4)}`); // 判断是否含有某元素 hashMap2.set(4, 123); // 增加元素
console.info(`result: ${hashMap.get('a')}`); // 访问元素 console.info(`result: ${hashMap2.hasKey(4)}`); // 判断是否含有某元素
console.info(`result: ${hashMap1.get('a')}`); // 访问元素
// TreeMap // TreeMap
import TreeMap from '@ohos.util.TreeMap'; // 导入TreeMap模块 import TreeMap from '@ohos.util.TreeMap'; // 导入TreeMap模块
let treeMap = new TreeMap(); let treeMap: TreeMap<string, number> = new TreeMap();
treeMap.set('a', 123); treeMap.set('a', 123);
treeMap.set('6', 356); // 增加元素 treeMap.set('6', 356); // 增加元素
console.info(`result: ${treeMap.get('a')}`); // 访问元素 console.info(`result: ${treeMap.get('a')}`); // 访问元素
...@@ -235,7 +236,7 @@ console.info(`result: ${treeMap.getLastKey()}`); // 访问尾元素 ...@@ -235,7 +236,7 @@ console.info(`result: ${treeMap.getLastKey()}`); // 访问尾元素
// LightWeightMap // LightWeightMap
import LightWeightMap from '@ohos.util.LightWeightMap'; // 导入LightWeightMap模块 import LightWeightMap from '@ohos.util.LightWeightMap'; // 导入LightWeightMap模块
let lightWeightMap = new LightWeightMap(); let lightWeightMap: LightWeightMap<string, number> = new LightWeightMap();
lightWeightMap.set('x', 123); lightWeightMap.set('x', 123);
lightWeightMap.set('8', 356); // 增加元素 lightWeightMap.set('8', 356); // 增加元素
console.info(`result: ${lightWeightMap.get('a')}`); // 访问元素 console.info(`result: ${lightWeightMap.get('a')}`); // 访问元素
...@@ -245,7 +246,7 @@ console.info(`result: ${lightWeightMap.getIndexOfKey('8')}`); // 访问元素 ...@@ -245,7 +246,7 @@ console.info(`result: ${lightWeightMap.getIndexOfKey('8')}`); // 访问元素
// PlainArray // PlainArray
import PlainArray from '@ohos.util.PlainArray' // 导入PlainArray模块 import PlainArray from '@ohos.util.PlainArray' // 导入PlainArray模块
let plainArray = new PlainArray(); let plainArray: PlainArray<string> = new PlainArray();
plainArray.add(1, 'sdd'); plainArray.add(1, 'sdd');
plainArray.add(2, 'sff'); // 增加元素 plainArray.add(2, 'sff'); // 增加元素
console.info(`result: ${plainArray.get(1)}`); // 访问元素 console.info(`result: ${plainArray.get(1)}`); // 访问元素
......
...@@ -5,24 +5,25 @@ Promise和async/await提供异步并发能力,适用于单次I/O任务的场 ...@@ -5,24 +5,25 @@ Promise和async/await提供异步并发能力,适用于单次I/O任务的场
1. 实现单次I/O任务逻辑。 1. 实现单次I/O任务逻辑。
```js ```js
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
async function write(data: string, filePath: string) {
let file = await fs.open(filePath, fs.OpenMode.READ_WRITE); async function write(data: string, filePath: string): Promise<void> {
fs.write(file.fd, data).then((writeLen) => { let file: fs.File = await fs.open(filePath, fs.OpenMode.READ_WRITE);
fs.write(file.fd, data).then((writeLen: number) => {
fs.close(file); fs.close(file);
}).catch((err) => { }).catch((err: BusinessError) => {
console.error(`Failed to write data. Code is ${err.code}, message is ${err.message}`); console.error(`Failed to write data. Code is ${err.code}, message is ${err.message}`);
}) })
} }
``` ```
2. 采用异步能力调用单次I/O任务。示例中的filePath的获取方式请参见[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径) 2. 采用异步能力调用单次I/O任务。示例中的filePath的获取方式请参见[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径)
```js ```js
let filePath = ...; // 应用文件路径 let filePath: string = ...; // 应用文件路径
write('Hello World!', filePath).then(() => { write('Hello World!', filePath).then(() => {
console.info('Succeeded in writing data.'); console.info('Succeeded in writing data.');
}) })
......
...@@ -25,18 +25,16 @@ ...@@ -25,18 +25,16 @@
```ts ```ts
// Handle.ts 代码 // Handle.ts 代码
export default class Handle { export default class Handle {
static getInstance() { static getInstance(): void {
// 返回单例对象 // 返回单例对象
} }
static syncGet() { static syncGet(): void {
// 同步Get方法 // 同步Get方法
return;
} }
static syncSet(num: number) { static syncSet(num: number): void {
// 同步Set方法 // 同步Set方法
return;
} }
} }
``` ```
...@@ -51,7 +49,7 @@ import Handle from './Handle'; // 返回静态句柄 ...@@ -51,7 +49,7 @@ import Handle from './Handle'; // 返回静态句柄
// 步骤1: 定义并发函数,内部调用同步方法 // 步骤1: 定义并发函数,内部调用同步方法
@Concurrent @Concurrent
function func(num: number) { function func(num: number): boolean {
// 调用静态类对象中实现的同步等待调用 // 调用静态类对象中实现的同步等待调用
Handle.syncSet(num); Handle.syncSet(num);
// 或者调用单例对象中实现的同步等待调用 // 或者调用单例对象中实现的同步等待调用
...@@ -60,13 +58,11 @@ function func(num: number) { ...@@ -60,13 +58,11 @@ function func(num: number) {
} }
// 步骤2: 创建任务并执行 // 步骤2: 创建任务并执行
async function asyncGet() { async function asyncGet(): Promise<void> {
// 创建task并传入函数func // 创建task并传入函数func
let task = new taskpool.Task(func, 1); let task: taskpool.Task = new taskpool.Task(func, 1);
// 执行task任务,获取结果res // 执行task任务并对同步逻辑后的结果进行操作
let res = await taskpool.execute(task); console.info(String(await taskpool.execute(task)));
// 对同步逻辑后的结果进行操作
console.info(String(res));
} }
@Entry @Entry
...@@ -98,15 +94,15 @@ struct Index { ...@@ -98,15 +94,15 @@ struct Index {
当一系列同步任务需要使用同一个句柄调度,或者需要依赖某个类对象调度,无法在不同任务池之间共享时,需要使用Worker。 当一系列同步任务需要使用同一个句柄调度,或者需要依赖某个类对象调度,无法在不同任务池之间共享时,需要使用Worker。
1. 在主线程中创建Worker对象,同时接收Worker线程发送回来的消息。 1. 在主线程中创建Worker对象,同时接收Worker线程发送回来的消息。
```js ```js
import worker from '@ohos.worker'; import worker from '@ohos.worker';
@Entry @Entry
@Component @Component
struct Index { struct Index {
@State message: string = 'Hello World'; @State message: string = 'Hello World';
build() { build() {
Row() { Row() {
Column() { Column() {
...@@ -114,7 +110,7 @@ struct Index { ...@@ -114,7 +110,7 @@ struct Index {
.fontSize(50) .fontSize(50)
.fontWeight(FontWeight.Bold) .fontWeight(FontWeight.Bold)
.onClick(() => { .onClick(() => {
let w = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); let w: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts');
w.onmessage = function (d) { w.onmessage = function (d) {
// 接收Worker子线程的结果 // 接收Worker子线程的结果
} }
...@@ -137,28 +133,28 @@ struct Index { ...@@ -137,28 +133,28 @@ struct Index {
``` ```
2. 在Worker线程中绑定Worker对象,同时处理同步任务逻辑。 2. 在Worker线程中绑定Worker对象,同时处理同步任务逻辑。
```js ```js
// handle.ts代码 // handle.ts代码
export default class Handle { export default class Handle {
syncGet() { syncGet() {
return; return;
} }
syncSet(num: number) { syncSet(num: number) {
return; return;
} }
} }
// Worker.ts代码 // Worker.ts代码
import worker, { ThreadWorkerGlobalScope, MessageEvents } from '@ohos.worker'; import worker, { ThreadWorkerGlobalScope, MessageEvents } from '@ohos.worker';
import Handle from './handle.ts' // 返回句柄 import Handle from './handle.ts' // 返回句柄
var workerPort : ThreadWorkerGlobalScope = worker.workerPort; var workerPort : ThreadWorkerGlobalScope = worker.workerPort;
// 无法传输的句柄,所有操作依赖此句柄 // 无法传输的句柄,所有操作依赖此句柄
var handler = new Handle() var handler = new Handle()
// Worker线程的onmessage逻辑 // Worker线程的onmessage逻辑
workerPort.onmessage = function(e : MessageEvents) { workerPort.onmessage = function(e : MessageEvents) {
switch (e.data.type) { switch (e.data.type) {
......
...@@ -102,9 +102,9 @@ TaskPool支持开发者在主线程封装任务抛给任务队列,系统选择 ...@@ -102,9 +102,9 @@ TaskPool支持开发者在主线程封装任务抛给任务队列,系统选择
```js ```js
// API 9及之后版本使用: // API 9及之后版本使用:
const worker1 = new worker.ThreadWorker(scriptURL); const worker1: worker.ThreadWorker = new worker.ThreadWorker(scriptURL);
// API 8及之前版本使用: // API 8及之前版本使用:
const worker1 = new worker.Worker(scriptURL); const worker1: worker.ThreadWorker = new worker.Worker(scriptURL);
``` ```
构造函数需要传入Worker的路径(scriptURL),Worker文件存放位置默认路径为Worker文件所在目录与pages目录属于同级。 构造函数需要传入Worker的路径(scriptURL),Worker文件存放位置默认路径为Worker文件所在目录与pages目录属于同级。
...@@ -119,15 +119,15 @@ const worker1 = new worker.Worker(scriptURL); ...@@ -119,15 +119,15 @@ const worker1 = new worker.Worker(scriptURL);
```js ```js
// 写法一 // 写法一
// Stage模型-目录同级(entry模块下,workers目录与pages目录同级) // Stage模型-目录同级(entry模块下,workers目录与pages目录同级)
const worker1 = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts', {name:"first worker in Stage model"}); const worker1: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts', {name:"first worker in Stage model"});
// Stage模型-目录不同级(entry模块下,workers目录是pages目录的子目录) // Stage模型-目录不同级(entry模块下,workers目录是pages目录的子目录)
const worker2 = new worker.ThreadWorker('entry/ets/pages/workers/MyWorker.ts'); const worker2: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/pages/workers/MyWorker.ts');
// 写法二 // 写法二
// Stage模型-目录同级(entry模块下,workers目录与pages目录同级),假设bundlename是com.example.workerdemo // Stage模型-目录同级(entry模块下,workers目录与pages目录同级),假设bundlename是com.example.workerdemo
const worker3 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/workers/worker'); const worker3: worker.ThreadWorker = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/workers/worker');
// Stage模型-目录不同级(entry模块下,workers目录是pages目录的子目录),假设bundlename是com.example.workerdemo // Stage模型-目录不同级(entry模块下,workers目录是pages目录的子目录),假设bundlename是com.example.workerdemo
const worker4 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/pages/workers/worker'); const worker4: worker.ThreadWorker = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/pages/workers/worker');
``` ```
...@@ -151,9 +151,9 @@ const worker4 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/et ...@@ -151,9 +151,9 @@ const worker4 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/et
```js ```js
// FA模型-目录同级(entry模块下,workers目录与pages目录同级) // FA模型-目录同级(entry模块下,workers目录与pages目录同级)
const worker1 = new worker.ThreadWorker('workers/worker.js', {name:'first worker in FA model'}); const worker1: worker.ThreadWorker = new worker.ThreadWorker('workers/worker.js', {name:'first worker in FA model'});
// FA模型-目录不同级(entry模块下,workers目录与pages目录的父目录同级) // FA模型-目录不同级(entry模块下,workers目录与pages目录的父目录同级)
const worker2 = new worker.ThreadWorker('../workers/worker.js'); const worker2: worker.ThreadWorker = new worker.ThreadWorker('../workers/worker.js');
``` ```
......
...@@ -17,22 +17,22 @@ XML解析及转换需要确保传入的XML数据符合标准格式。 ...@@ -17,22 +17,22 @@ XML解析及转换需要确保传入的XML数据符合标准格式。
此处以XML转为JavaScript对象后获取其标签值为例,说明转换效果。 此处以XML转为JavaScript对象后获取其标签值为例,说明转换效果。
1. 引入模块。 1. 引入模块。
```js ```js
import convertxml from '@ohos.convertxml'; import convertxml from '@ohos.convertxml';
``` ```
2. 输入待转换的XML,设置转换选项。 2. 输入待转换的XML,设置转换选项。
```js ```js
let xml = let xml: string =
'<?xml version="1.0" encoding="utf-8"?>' + '<?xml version="1.0" encoding="utf-8"?>' +
'<note importance="high" logged="true">' + '<note importance="high" logged="true">' +
' <title>Happy</title>' + ' <title>Happy</title>' +
' <todo>Work</todo>' + ' <todo>Work</todo>' +
' <todo>Play</todo>' + ' <todo>Play</todo>' +
'</note>'; '</note>';
let options = { let options: convertxml.ConvertOptions = {
// trim: false 转换后是否删除文本前后的空格,否 // trim: false 转换后是否删除文本前后的空格,否
// declarationKey: "_declaration" 转换后文件声明使用_declaration来标识 // declarationKey: "_declaration" 转换后文件声明使用_declaration来标识
// instructionKey: "_instruction" 转换后指令使用_instruction标识 // instructionKey: "_instruction" 转换后指令使用_instruction标识
...@@ -51,7 +51,7 @@ XML解析及转换需要确保传入的XML数据符合标准格式。 ...@@ -51,7 +51,7 @@ XML解析及转换需要确保传入的XML数据符合标准格式。
attributesKey: "_attributes", attributesKey: "_attributes",
textKey: "_text", textKey: "_text",
cdataKey: "_cdata", cdataKey: "_cdata",
docTypeKey: "_doctype", doctypeKey: "_doctype",
commentKey: "_comment", commentKey: "_comment",
parentKey: "_parent", parentKey: "_parent",
typeKey: "_type", typeKey: "_type",
...@@ -61,24 +61,17 @@ XML解析及转换需要确保传入的XML数据符合标准格式。 ...@@ -61,24 +61,17 @@ XML解析及转换需要确保传入的XML数据符合标准格式。
``` ```
3. 调用转换函数,打印结果。 3. 调用转换函数,打印结果。
```js ```js
let conv = new convertxml.ConvertXML(); let conv: convertxml.ConvertXML = new convertxml.ConvertXML();
let result = conv.convertToJSObject(xml, options); let result: object = conv.convertToJSObject(xml, options);
let strRes = JSON.stringify(result); // 将js对象转换为json字符串,用于显式输出 let strRes: string = JSON.stringify(result); // 将js对象转换为json字符串,用于显式输出
console.info(strRes); console.info(strRes);
// 也可以直接处理转换后的JS对象,获取标签值
let title = result['_elements'][0]['_elements'][0]['_elements'][0]['_text']; // 解析<title>标签对应的值
let todo = result['_elements'][0]['_elements'][1]['_elements'][0]['_text']; // 解析<todo>标签对应的值
let todo2 = result['_elements'][0]['_elements'][2]['_elements'][0]['_text']; // 解析<todo>标签对应的值
console.info(title); // Happy
console.info(todo); // Work
console.info(todo2); // Play
``` ```
输出结果如下所示: 输出结果如下所示:
```js ```js
strRes: strRes:
{"_declaration":{"_attributes":{"version":"1.0","encoding":"utf-8"}},"_elements":[{"_type":"element","_name":"note", {"_declaration":{"_attributes":{"version":"1.0","encoding":"utf-8"}},"_elements":[{"_type":"element","_name":"note",
...@@ -86,7 +79,4 @@ XML解析及转换需要确保传入的XML数据符合标准格式。 ...@@ -86,7 +79,4 @@ XML解析及转换需要确保传入的XML数据符合标准格式。
"_elements":[{"_type":"text","_text":"Happy"}]},{"_type":"element","_name":"todo", "_elements":[{"_type":"text","_text":"Happy"}]},{"_type":"element","_name":"todo",
"_elements":[{"_type":"text","_text":"Work"}]},{"_type":"element","_name":"todo", "_elements":[{"_type":"text","_text":"Work"}]},{"_type":"element","_name":"todo",
"_elements":[{"_type":"text","_text":"Play"}]}]}]} "_elements":[{"_type":"text","_text":"Play"}]}]}]}
title:Happy
todo:Work
todo2:Play
``` ```
...@@ -23,27 +23,27 @@ XML模块提供XmlSerializer类来生成XML文件,输入为固定长度的Arra ...@@ -23,27 +23,27 @@ XML模块提供XmlSerializer类来生成XML文件,输入为固定长度的Arra
XML模块的API接口可以参考[@ohos.xml](../reference/apis/js-apis-xml.md)的详细描述,按需求调用对应函数可以生成一份完整的XML文件。 XML模块的API接口可以参考[@ohos.xml](../reference/apis/js-apis-xml.md)的详细描述,按需求调用对应函数可以生成一份完整的XML文件。
1. 引入模块。 1. 引入模块。
```js ```js
import xml from '@ohos.xml'; import xml from '@ohos.xml';
import util from '@ohos.util'; import util from '@ohos.util';
``` ```
2. 创建缓冲区,构造XmlSerializer对象(可以基于Arraybuffer构造XmlSerializer对象, 也可以基于DataView构造XmlSerializer对象)。 2. 创建缓冲区,构造XmlSerializer对象(可以基于Arraybuffer构造XmlSerializer对象, 也可以基于DataView构造XmlSerializer对象)。
```js ```js
// 1.基于Arraybuffer构造XmlSerializer对象 // 1.基于Arraybuffer构造XmlSerializer对象
let arrayBuffer = new ArrayBuffer(2048); // 创建一个2048字节的缓冲区 let arrayBuffer: ArrayBuffer = new ArrayBuffer(2048); // 创建一个2048字节的缓冲区
let thatSer = new xml.XmlSerializer(arrayBuffer); // 基于Arraybuffer构造XmlSerializer对象 let thatSer: xml.XmlSerializer = new xml.XmlSerializer(arrayBuffer); // 基于Arraybuffer构造XmlSerializer对象
// 2.基于DataView构造XmlSerializer对象 // 2.基于DataView构造XmlSerializer对象
let arrayBuffer = new ArrayBuffer(2048); // 创建一个2048字节的缓冲区 let arrayBuffer: ArrayBuffer = new ArrayBuffer(2048); // 创建一个2048字节的缓冲区
let dataView = new DataView(arrayBuffer); // 使用DataView对象操作ArrayBuffer对象 let dataView: DataView = new DataView(arrayBuffer); // 使用DataView对象操作ArrayBuffer对象
let thatSer = new xml.XmlSerializer(dataView); // 基于DataView构造XmlSerializer对象 let thatSer: xml.XmlSerializer = new xml.XmlSerializer(dataView); // 基于DataView构造XmlSerializer对象
``` ```
3. 调用XML元素生成函数。 3. 调用XML元素生成函数。
```js ```js
thatSer.setDeclaration(); // 写入xml的声明 thatSer.setDeclaration(); // 写入xml的声明
thatSer.startElement('bookstore'); // 写入元素开始标记 thatSer.startElement('bookstore'); // 写入元素开始标记
...@@ -64,17 +64,17 @@ XML模块的API接口可以参考[@ohos.xml](../reference/apis/js-apis-xml.md) ...@@ -64,17 +64,17 @@ XML模块的API接口可以参考[@ohos.xml](../reference/apis/js-apis-xml.md)
``` ```
4. 使用Uint8Array操作Arraybuffer,调用TextDecoder对Uint8Array解码后输出。 4. 使用Uint8Array操作Arraybuffer,调用TextDecoder对Uint8Array解码后输出。
```js ```js
let view = new Uint8Array(arrayBuffer); // 使用Uint8Array读取arrayBuffer的数据 let view: Uint8Array = new Uint8Array(arrayBuffer); // 使用Uint8Array读取arrayBuffer的数据
let textDecoder = util.TextDecoder.create(); // 调用util模块的TextDecoder类 let textDecoder: util.TextDecoder = util.TextDecoder.create(); // 调用util模块的TextDecoder类
let res = textDecoder.decodeWithStream(view); // 对view解码 let res: string = textDecoder.decodeWithStream(view); // 对view解码
console.info(res); console.info(res);
``` ```
输出结果如下: 输出结果如下:
```js ```js
<?xml version=\"1.0\" encoding=\"utf-8\"?><bookstore>\r\n <book category=\"COOKING\">\r\n <title lang=\"en\">Everyday</title>\r\n <author>Giada</author>\r\n <year>2005</year>\r\n </book>\r\n</bookstore> <?xml version=\"1.0\" encoding=\"utf-8\"?><bookstore>\r\n <book category=\"COOKING\">\r\n <title lang=\"en\">Everyday</title>\r\n <author>Giada</author>\r\n <year>2005</year>\r\n </book>\r\n</bookstore>
``` ```
...@@ -28,7 +28,7 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A ...@@ -28,7 +28,7 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A
## 解析XML标签和标签值 ## 解析XML标签和标签值
1. 引入模块。 1. 引入模块。
```js ```js
import xml from '@ohos.xml'; import xml from '@ohos.xml';
import util from '@ohos.util'; // 需要使用util模块函数对文件编码 import util from '@ohos.util'; // 需要使用util模块函数对文件编码
...@@ -37,29 +37,29 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A ...@@ -37,29 +37,29 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A
2. 对XML文件编码后调用XmlPullParser。 2. 对XML文件编码后调用XmlPullParser。
可以基于ArrayBuffer构造XmlPullParser对象, 也可以基于DataView构造XmlPullParser对象。 可以基于ArrayBuffer构造XmlPullParser对象, 也可以基于DataView构造XmlPullParser对象。
```js ```js
let strXml = let strXml: string =
'<?xml version="1.0" encoding="utf-8"?>' + '<?xml version="1.0" encoding="utf-8"?>' +
'<note importance="high" logged="true">' + '<note importance="high" logged="true">' +
'<title>Play</title>' + '<title>Play</title>' +
'<lens>Work</lens>' + '<lens>Work</lens>' +
'</note>'; '</note>';
let textEncoder = new util.TextEncoder(); let textEncoder: util.TextEncoder = new util.TextEncoder();
let arrBuffer = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码
// 1.基于ArrayBuffer构造XmlPullParser对象 // 1.基于ArrayBuffer构造XmlPullParser对象
let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8');
// 2.基于DataView构造XmlPullParser对象 // 2.基于DataView构造XmlPullParser对象
let dataView = new DataView(arrBuffer.buffer); let dataView: DataView = new DataView(arrBuffer.buffer);
let that = new xml.XmlPullParser(dataView, 'UTF-8'); let that: xml.XmlPullParser = new xml.XmlPullParser(dataView, 'UTF-8');
``` ```
3. 自定义回调函数,本例直接打印出标签及标签值。 3. 自定义回调函数,本例直接打印出标签及标签值。
```js ```js
let str = ''; let str: string = '';
function func(name, value){ function func(name: string, value: string): boolean {
str = name + value; str = name + value;
console.info(str); console.info(str);
return true; //true:继续解析 false:停止解析 return true; //true:继续解析 false:停止解析
...@@ -67,15 +67,15 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A ...@@ -67,15 +67,15 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A
``` ```
4. 设置解析选项,调用parse函数。 4. 设置解析选项,调用parse函数。
```js ```js
let options = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func}; let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func};
that.parse(options); that.parse(options);
``` ```
输出结果如下所示: 输出结果如下所示:
```js ```js
note note
title title
...@@ -91,48 +91,48 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A ...@@ -91,48 +91,48 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A
## 解析XML属性和属性值 ## 解析XML属性和属性值
1. 引入模块。 1. 引入模块。
```js ```js
import xml from '@ohos.xml'; import xml from '@ohos.xml';
import util from '@ohos.util'; // 需要使用util模块函数对文件编码 import util from '@ohos.util'; // 需要使用util模块函数对文件编码
``` ```
2. 对XML文件编码后调用XmlPullParser。 2. 对XML文件编码后调用XmlPullParser。
```js ```js
let strXml = let strXml: string =
'<?xml version="1.0" encoding="utf-8"?>' + '<?xml version="1.0" encoding="utf-8"?>' +
'<note importance="high" logged="true">' + '<note importance="high" logged="true">' +
' <title>Play</title>' + ' <title>Play</title>' +
' <title>Happy</title>' + ' <title>Happy</title>' +
' <lens>Work</lens>' + ' <lens>Work</lens>' +
'</note>'; '</note>';
let textEncoder = new util.TextEncoder(); let textEncoder: util.TextEncoder = new util.TextEncoder();
let arrBuffer = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码
let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8');
``` ```
3. 自定义回调函数,本例直接打印出属性及属性值。 3. 自定义回调函数,本例直接打印出属性及属性值。
```js ```js
let str = ''; let str: string = '';
function func(name, value){ function func(name: string, value: string): boolean {
str += name + ' ' + value + ' '; str += name + ' ' + value + ' ';
return true; // true:继续解析 false:停止解析 return true; // true:继续解析 false:停止解析
} }
``` ```
4. 设置解析选项,调用parse函数。 4. 设置解析选项,调用parse函数。
```js ```js
let options = {supportDoctype:true, ignoreNameSpace:true, attributeValueCallbackFunction:func}; let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, attributeValueCallbackFunction:func};
that.parse(options); that.parse(options);
console.info(str); // 一次打印出所有的属性及其值 console.info(str); // 一次打印出所有的属性及其值
``` ```
输出结果如下所示: 输出结果如下所示:
```js ```js
importance high logged true // note节点的属性及属性值 importance high logged true // note节点的属性及属性值
``` ```
...@@ -141,30 +141,30 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A ...@@ -141,30 +141,30 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A
## 解析XML事件类型和元素深度 ## 解析XML事件类型和元素深度
1. 引入模块。 1. 引入模块。
```js ```js
import xml from '@ohos.xml'; import xml from '@ohos.xml';
import util from '@ohos.util'; // 需要使用util模块函数对文件编码 import util from '@ohos.util'; // 需要使用util模块函数对文件编码
``` ```
2. 对XML文件编码后调用XmlPullParser。 2. 对XML文件编码后调用XmlPullParser。
```js ```js
let strXml = let strXml: string =
'<?xml version="1.0" encoding="utf-8"?>' + '<?xml version="1.0" encoding="utf-8"?>' +
'<note importance="high" logged="true">' + '<note importance="high" logged="true">' +
'<title>Play</title>' + '<title>Play</title>' +
'</note>'; '</note>';
let textEncoder = new util.TextEncoder(); let textEncoder: util.TextEncoder = new util.TextEncoder();
let arrBuffer = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码
let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8');
``` ```
3. 自定义回调函数,本例直接打印元素事件类型及元素深度。 3. 自定义回调函数,本例直接打印元素事件类型及元素深度。
```js ```js
let str = ''; let str: string = '';
function func(name, value){ function func(name: string, value: xml.ParseInfo): boolean {
str = name + ' ' + value.getDepth(); // getDepth 获取元素的当前深度 str = name + ' ' + value.getDepth(); // getDepth 获取元素的当前深度
console.info(str) console.info(str)
return true; //true:继续解析 false:停止解析 return true; //true:继续解析 false:停止解析
...@@ -172,15 +172,15 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A ...@@ -172,15 +172,15 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A
``` ```
4. 设置解析选项,调用parse函数。 4. 设置解析选项,调用parse函数。
```js ```js
let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func}; let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func};
that.parse(options); that.parse(options);
``` ```
输出结果如下所示: 输出结果如下所示:
```js ```js
0 0 // 0:<?xml version="1.0" encoding="utf-8"?> 对应事件类型START_DOCUMENT值为0 0:起始深度为0 0 0 // 0:<?xml version="1.0" encoding="utf-8"?> 对应事件类型START_DOCUMENT值为0 0:起始深度为0
2 1 // 2:<note importance="high" logged="true"> 对应事件类型START_TAG值为2 1:深度为1 2 1 // 2:<note importance="high" logged="true"> 对应事件类型START_TAG值为2 1:深度为1
...@@ -201,36 +201,36 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A ...@@ -201,36 +201,36 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A
import xml from '@ohos.xml'; import xml from '@ohos.xml';
import util from '@ohos.util'; import util from '@ohos.util';
let strXml = let strXml: string =
'<?xml version="1.0" encoding="UTF-8"?>' + '<?xml version="1.0" encoding="UTF-8"?>' +
'<book category="COOKING">' + '<book category="COOKING">' +
'<title lang="en">Everyday</title>' + '<title lang="en">Everyday</title>' +
'<author>Giada</author>' + '<author>Giada</author>' +
'</book>'; '</book>';
let textEncoder = new util.TextEncoder(); let textEncoder: util.TextEncoder = new util.TextEncoder();
let arrBuffer = textEncoder.encodeInto(strXml); let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml);
let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8');
let str = ''; let str: string = '';
function tagFunc(name, value) { function tagFunc(name: string, value: string): boolean {
str = name + value; str = name + value;
console.info('tag-' + str); console.info('tag-' + str);
return true; return true;
} }
function attFunc(name, value) { function attFunc(name: string, value: string): boolean {
str = name + ' ' + value; str = name + ' ' + value;
console.info('attri-' + str); console.info('attri-' + str);
return true; return true;
} }
function tokenFunc(name, value) { function tokenFunc(name: string, value: xml.ParseInfo): boolean {
str = name + ' ' + value.getDepth(); str = name + ' ' + value.getDepth();
console.info('token-' + str); console.info('token-' + str);
return true; return true;
} }
let options = { let options: xml.ParseOptions = {
supportDocType: true, supportDocType: true,
ignoreNameSpace: true, ignoreNameSpace: true,
tagValueCallbackFunction: tagFunc, tagValueCallbackFunction: tagFunc,
......
...@@ -51,12 +51,12 @@ execute(func: Function, ...args: unknown[]): Promise\<unknown> ...@@ -51,12 +51,12 @@ execute(func: Function, ...args: unknown[]): Promise\<unknown>
```ts ```ts
@Concurrent @Concurrent
function printArgs(args) { function printArgs(args: number): number {
console.log("printArgs: " + args); console.log("printArgs: " + args);
return args; return args;
} }
taskpool.execute(printArgs, 100).then((value) => { // 100: test number taskpool.execute(printArgs, 100).then((value: number) => { // 100: test number
console.log("taskpool result: " + value); console.log("taskpool result: " + value);
}); });
``` ```
...@@ -96,13 +96,13 @@ execute(task: Task, priority?: Priority): Promise\<unknown> ...@@ -96,13 +96,13 @@ execute(task: Task, priority?: Priority): Promise\<unknown>
```ts ```ts
@Concurrent @Concurrent
function printArgs(args) { function printArgs(args: number): number {
console.log("printArgs: " + args); console.log("printArgs: " + args);
return args; return args;
} }
let task = new taskpool.Task(printArgs, 100); // 100: test number let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
taskpool.execute(task).then((value) => { taskpool.execute(task).then((value: number) => {
console.log("taskpool result: " + value); console.log("taskpool result: " + value);
}); });
``` ```
...@@ -140,32 +140,28 @@ execute(group: TaskGroup, priority?: Priority): Promise<unknown[]> ...@@ -140,32 +140,28 @@ execute(group: TaskGroup, priority?: Priority): Promise<unknown[]>
```ts ```ts
@Concurrent @Concurrent
function printArgs(args) { function printArgs(args: number): number {
console.log("printArgs: " + args); console.log("printArgs: " + args);
return args; return args;
} }
let taskGroup1 = new taskpool.TaskGroup(); let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
taskGroup1.addTask(printArgs, 10); // 10: test number taskGroup1.addTask(printArgs, 10); // 10: test number
taskGroup1.addTask(printArgs, 20); // 20: test number taskGroup1.addTask(printArgs, 20); // 20: test number
taskGroup1.addTask(printArgs, 30); // 30: test number taskGroup1.addTask(printArgs, 30); // 30: test number
let taskGroup2 = new taskpool.TaskGroup(); let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
let task1 = new taskpool.Task(printArgs, 100); // 100: test number let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
let task2 = new taskpool.Task(printArgs, 200); // 200: test number let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
let task3 = new taskpool.Task(printArgs, 300); // 300: test number let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number
taskGroup2.addTask(task1); taskGroup2.addTask(task1);
taskGroup2.addTask(task2); taskGroup2.addTask(task2);
taskGroup2.addTask(task3); taskGroup2.addTask(task3);
taskpool.execute(taskGroup1).then((res) => { taskpool.execute(taskGroup1).then((res: Array<number>) => {
console.info("taskpool execute res is:" + res); console.info("taskpool execute res is:" + res);
}).catch((e) => {
console.error("taskpool execute error is:" + e);
}); });
taskpool.execute(taskGroup2).then((res) => { taskpool.execute(taskGroup2).then((res: Array<number>) => {
console.info("taskpool execute res is:" + res); console.info("taskpool execute res is:" + res);
}).catch((e) => {
console.error("taskpool execute error is:" + e);
}); });
``` ```
...@@ -198,41 +194,39 @@ cancel(task: Task): void ...@@ -198,41 +194,39 @@ cancel(task: Task): void
```ts ```ts
@Concurrent @Concurrent
function inspectStatus(arg) { function inspectStatus(arg: number): number {
// 第一时间检查取消并回复 // 第一时间检查取消并回复
if (taskpool.Task.isCanceled()) { if (taskpool.Task.isCanceled()) {
console.log("task has been canceled before 2s sleep."); console.log("task has been canceled before 2s sleep.");
return arg + 2; return arg + 2;
} }
// 2s sleep // 2s sleep
let t = Date.now(); let t: number = Date.now();
while (Date.now() - t < 2000) { while (Date.now() - t < 2000) {
continue; continue;
} }
// 第二次检查取消并作出响应 // 第二次检查取消并作出响应
if (taskpool.Task.isCanceled()) { if (taskpool.Task.isCanceled()) {
console.log("task has been canceled after 2s sleep."); console.log("task has been canceled after 2s sleep.");
return arg + 3; return arg + 3;
} }
return arg + 1; return arg + 1;
} }
let task1 = new taskpool.Task(inspectStatus, 100); // 100: test number let task1: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
let task2 = new taskpool.Task(inspectStatus, 200); // 200: test number let task2: taskpool.Task = new taskpool.Task(inspectStatus, 200); // 200: test number
let task3 = new taskpool.Task(inspectStatus, 300); // 300: test number let task3: taskpool.Task = new taskpool.Task(inspectStatus, 300); // 300: test number
let task4 = new taskpool.Task(inspectStatus, 400); // 400: test number let task4: taskpool.Task = new taskpool.Task(inspectStatus, 400); // 400: test number
let task5 = new taskpool.Task(inspectStatus, 500); // 500: test number let task5: taskpool.Task = new taskpool.Task(inspectStatus, 500); // 500: test number
let task6 = new taskpool.Task(inspectStatus, 600); // 600: test number let task6: taskpool.Task = new taskpool.Task(inspectStatus, 600); // 600: test number
taskpool.execute(task1).then((res)=>{ taskpool.execute(task1).then((res: number)=>{
console.log("taskpool test result: " + res); console.log("taskpool test result: " + res);
}).catch((err) => {
console.log("taskpool test occur error: " + err);
}); });
let res2 = taskpool.execute(task2); taskpool.execute(task2);
let res3 = taskpool.execute(task3); taskpool.execute(task3);
let res4 = taskpool.execute(task4); taskpool.execute(task4);
let res5 = taskpool.execute(task5); taskpool.execute(task5);
let res6 = taskpool.execute(task6); taskpool.execute(task6);
// 1s后取消task // 1s后取消task
setTimeout(()=>{ setTimeout(()=>{
taskpool.cancel(task1);}, 1000); taskpool.cancel(task1);}, 1000);
...@@ -264,23 +258,23 @@ cancel(group: TaskGroup): void ...@@ -264,23 +258,23 @@ cancel(group: TaskGroup): void
```ts ```ts
@Concurrent @Concurrent
function printArgs(args) { function printArgs(args: number): number {
let t = Date.now(); let t: number = Date.now();
while (Date.now() - t < 2000) { while (Date.now() - t < 2000) {
continue; continue;
} }
console.log("printArgs: " + args); console.log("printArgs: " + args);
return args; return args;
} }
let taskGroup1 = new taskpool.TaskGroup(); let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
taskGroup1.addTask(printArgs, 10); // 10: test number taskGroup1.addTask(printArgs, 10); // 10: test number
let taskGroup2 = new taskpool.TaskGroup(); let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
taskGroup2.addTask(printArgs, 100); // 100: test number taskGroup2.addTask(printArgs, 100); // 100: test number
taskpool.execute(taskGroup1).then((res)=>{ taskpool.execute(taskGroup1).then((res: Array<number>)=>{
console.info("taskGroup1 res is:" + res) console.info("taskGroup1 res is:" + res)
}); });
taskpool.execute(taskGroup2).then((res)=>{ taskpool.execute(taskGroup2).then((res: Array<number>)=>{
console.info("taskGroup2 res is:" + res) console.info("taskGroup2 res is:" + res)
}); });
setTimeout(()=>{ setTimeout(()=>{
...@@ -310,7 +304,7 @@ getTaskPoolInfo(): TaskPoolInfo ...@@ -310,7 +304,7 @@ getTaskPoolInfo(): TaskPoolInfo
**示例:** **示例:**
```ts ```ts
let taskpoolInfo = taskpool.getTaskPoolInfo(); let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo();
``` ```
## Priority ## Priority
...@@ -329,35 +323,29 @@ let taskpoolInfo = taskpool.getTaskPoolInfo(); ...@@ -329,35 +323,29 @@ let taskpoolInfo = taskpool.getTaskPoolInfo();
```ts ```ts
@Concurrent @Concurrent
function printArgs(args) { function printArgs(args: number): number {
console.log("printArgs: " + args); console.log("printArgs: " + args);
return args; return args;
} }
let task = new taskpool.Task(printArgs, 100); // 100: test number let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
let highCount = 0; let highCount = 0;
let mediumCount = 0; let mediumCount = 0;
let lowCount = 0; let lowCount = 0;
let allCount = 100; let allCount = 100;
for (let i = 0; i < allCount; i++) { for (let i: number = 0; i < allCount; i++) {
taskpool.execute(task, taskpool.Priority.LOW).then((res: number) => { taskpool.execute(task, taskpool.Priority.LOW).then((res: number) => {
lowCount++; lowCount++;
console.log("taskpool lowCount is :" + lowCount); console.log("taskpool lowCount is :" + lowCount);
}).catch((e) => { });
console.error("low task error: " + e);
})
taskpool.execute(task, taskpool.Priority.MEDIUM).then((res: number) => { taskpool.execute(task, taskpool.Priority.MEDIUM).then((res: number) => {
mediumCount++; mediumCount++;
console.log("taskpool mediumCount is :" + mediumCount); console.log("taskpool mediumCount is :" + mediumCount);
}).catch((e) => { });
console.error("medium task error: " + e);
})
taskpool.execute(task, taskpool.Priority.HIGH).then((res: number) => { taskpool.execute(task, taskpool.Priority.HIGH).then((res: number) => {
highCount++; highCount++;
console.log("taskpool highCount is :" + highCount); console.log("taskpool highCount is :" + highCount);
}).catch((e) => { });
console.error("high task error: " + e);
})
} }
``` ```
...@@ -392,12 +380,12 @@ Task的构造函数。 ...@@ -392,12 +380,12 @@ Task的构造函数。
```ts ```ts
@Concurrent @Concurrent
function printArgs(args) { function printArgs(args: number): number {
console.log("printArgs: " + args); console.log("printArgs: " + args);
return args; return args;
} }
let task = new taskpool.Task(printArgs, "this is my first Task"); let task: taskpool.Task = new taskpool.Task(printArgs, "this is my first Task");
``` ```
### isCanceled<sup>10+</sup> ### isCanceled<sup>10+</sup>
...@@ -418,7 +406,7 @@ static isCanceled(): boolean ...@@ -418,7 +406,7 @@ static isCanceled(): boolean
```ts ```ts
@Concurrent @Concurrent
function inspectStatus(arg) { function inspectStatus(arg: number): number {
// do something // do something
if (taskpool.Task.isCanceled()) { if (taskpool.Task.isCanceled()) {
console.log("task has been canceled."); console.log("task has been canceled.");
...@@ -437,29 +425,29 @@ function inspectStatus(arg) { ...@@ -437,29 +425,29 @@ function inspectStatus(arg) {
```ts ```ts
@Concurrent @Concurrent
function inspectStatus(arg) { function inspectStatus(arg: number): number {
// 第一时间检查取消并回复 // 第一时间检查取消并回复
if (taskpool.Task.isCanceled()) { if (taskpool.Task.isCanceled()) {
console.log("task has been canceled before 2s sleep."); console.log("task has been canceled before 2s sleep.");
return arg + 2; return arg + 2;
} }
// 延时2s // 延时2s
let t = Date.now(); let t: number = Date.now();
while (Date.now() - t < 2000) { while (Date.now() - t < 2000) {
continue; continue;
} }
// 第二次检查取消并作出响应 // 第二次检查取消并作出响应
if (taskpool.Task.isCanceled()) { if (taskpool.Task.isCanceled()) {
console.log("task has been canceled after 2s sleep."); console.log("task has been canceled after 2s sleep.");
return arg + 3; return arg + 3;
} }
return arg + 1; return arg + 1;
} }
let task = new taskpool.Task(inspectStatus, 100); // 100: test number let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
taskpool.execute(task).then((res)=>{ taskpool.execute(task).then((res: number)=>{
console.log("taskpool test result: " + res); console.log("taskpool test result: " + res);
}).catch((err) => { }).catch((err: string) => {
console.log("taskpool test occur error: " + err); console.log("taskpool test occur error: " + err);
}); });
// 不调用cancel,isCanceled()默认返回false,task执行的结果为101 // 不调用cancel,isCanceled()默认返回false,task执行的结果为101
...@@ -485,24 +473,24 @@ setTransferList(transfer?: ArrayBuffer[]): void ...@@ -485,24 +473,24 @@ setTransferList(transfer?: ArrayBuffer[]): void
**示例:** **示例:**
```ts ```ts
let buffer = new ArrayBuffer(8); let buffer: ArrayBuffer = new ArrayBuffer(8);
let view = new Uint8Array(buffer); let view: Uint8Array = new Uint8Array(buffer);
let buffer1 = new ArrayBuffer(16); let buffer1: ArrayBuffer = new ArrayBuffer(16);
let view1 = new Uint8Array(buffer1); let view1: Uint8Array = new Uint8Array(buffer1);
console.info("testTransfer view byteLength: " + view.byteLength); console.info("testTransfer view byteLength: " + view.byteLength);
console.info("testTransfer view1 byteLength: " + view1.byteLength); console.info("testTransfer view1 byteLength: " + view1.byteLength);
@Concurrent @Concurrent
function testTransfer(arg1, arg2) { function testTransfer(arg1: ArrayBuffer, arg2: ArrayBuffer): number {
console.info("testTransfer arg1 byteLength: " + arg1.byteLength); console.info("testTransfer arg1 byteLength: " + arg1.byteLength);
console.info("testTransfer arg2 byteLength: " + arg2.byteLength); console.info("testTransfer arg2 byteLength: " + arg2.byteLength);
return 100; return 100;
} }
let task = new taskpool.Task(testTransfer, view, view1); let task: taskpool.Task = new taskpool.Task(testTransfer, view, view1);
task.setTransferList([view.buffer, view1.buffer]); task.setTransferList([view.buffer, view1.buffer]);
taskpool.execute(task).then((res)=>{ taskpool.execute(task).then((res: number)=>{
console.info("test result: " + res); console.info("test result: " + res);
}).catch((e)=>{ }).catch((e: string)=>{
console.error("test catch: " + e); console.error("test catch: " + e);
}) })
console.info("testTransfer view byteLength: " + view.byteLength); console.info("testTransfer view byteLength: " + view.byteLength);
...@@ -563,12 +551,12 @@ addTask(func: Function, ...args: unknown[]): void ...@@ -563,12 +551,12 @@ addTask(func: Function, ...args: unknown[]): void
```ts ```ts
@Concurrent @Concurrent
function printArgs(args) { function printArgs(args: number): number {
console.log("printArgs: " + args); console.log("printArgs: " + args);
return args; return args;
} }
let taskGroup = new taskpool.TaskGroup(); let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup();
taskGroup.addTask(printArgs, 100); // 100: test number taskGroup.addTask(printArgs, 100); // 100: test number
``` ```
...@@ -598,13 +586,13 @@ addTask(task: Task): void ...@@ -598,13 +586,13 @@ addTask(task: Task): void
```ts ```ts
@Concurrent @Concurrent
function printArgs(args) { function printArgs(args: number): number {
console.log("printArgs: " + args); console.log("printArgs: " + args);
return args; return args;
} }
let taskGroup = new taskpool.TaskGroup(); let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup();
let task = new taskpool.Task(printArgs, 200); // 200: test number let task: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
taskGroup.addTask(task); taskGroup.addTask(task);
``` ```
...@@ -675,12 +663,6 @@ taskGroup.addTask(task); ...@@ -675,12 +663,6 @@ taskGroup.addTask(task);
### 序列化支持类型 ### 序列化支持类型
序列化支持类型包括:All Primitive Type(不包括symbol)、Date、String、RegExp、Array、Map、Set、Object、ArrayBuffer、TypedArray。 序列化支持类型包括:All Primitive Type(不包括symbol)、Date、String、RegExp、Array、Map、Set、Object、ArrayBuffer、TypedArray。
### 注意事项
- 仅支持在Stage模型且module的compileMode为esmodule的project中使用taskpool api。确认module的compileMode方法:查看当前module的build-profile.json5,在buildOption中补充"compileMode": "esmodule"。
- taskpool任务只支持引用入参传递或者import的变量,不支持使用闭包变量,使用装饰器@Concurrent进行拦截。
- taskpool任务只支持普通函数或者async函数,不支持类成员函数或者匿名函数,使用装饰器@Concurrent进行拦截。
- 装饰器@Concurrent仅支持在ets文件使用。
### 简单使用 ### 简单使用
**示例一** **示例一**
...@@ -688,22 +670,17 @@ taskGroup.addTask(task); ...@@ -688,22 +670,17 @@ taskGroup.addTask(task);
```ts ```ts
// 支持普通函数、引用入参传递 // 支持普通函数、引用入参传递
@Concurrent @Concurrent
function printArgs(args) { function printArgs(args: number): number {
console.log("func: " + args); console.log("func: " + args);
return args; return args;
} }
async function taskpoolExecute(): Promise<void> {
async function taskpoolExecute() {
// taskpool.execute(task) // taskpool.execute(task)
let task = new taskpool.Task(printArgs, "create task, then execute"); let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute");
let val1 = await taskpool.execute(task); console.log("taskpool.execute(task) result: " + await taskpool.execute(task));
console.log("taskpool.execute(task) result: " + val1);
// taskpool.execute(function) // taskpool.execute(function)
let val2 = await taskpool.execute(printArgs, "execute task by func"); console.log("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func"));
console.log("taskpool.execute(function) result: " + val2);
} }
taskpoolExecute(); taskpoolExecute();
``` ```
...@@ -711,7 +688,7 @@ taskpoolExecute(); ...@@ -711,7 +688,7 @@ taskpoolExecute();
```ts ```ts
// b.ets // b.ets
export let c = 2000; export let c: number = 2000;
``` ```
```ts ```ts
// 引用import变量 // 引用import变量
...@@ -719,7 +696,7 @@ export let c = 2000; ...@@ -719,7 +696,7 @@ export let c = 2000;
import { c } from "./b"; import { c } from "./b";
@Concurrent @Concurrent
function printArgs(a) { function printArgs(a: number): number {
console.log(a); console.log(a);
console.log(c); console.log(c);
return a; return a;
...@@ -727,13 +704,11 @@ function printArgs(a) { ...@@ -727,13 +704,11 @@ function printArgs(a) {
async function taskpoolExecute() { async function taskpoolExecute() {
// taskpool.execute(task) // taskpool.execute(task)
let task = new taskpool.Task(printArgs, "create task, then execute"); let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute");
let val1 = await taskpool.execute(task); console.log("taskpool.execute(task) result: " + await taskpool.execute(task));
console.log("taskpool.execute(task) result: " + val1);
// taskpool.execute(function) // taskpool.execute(function)
let val2 = await taskpool.execute(printArgs, "execute task by func"); console.log("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func"));
console.log("taskpool.execute(function) result: " + val2);
} }
taskpoolExecute(); taskpoolExecute();
...@@ -752,8 +727,10 @@ async function delayExcute() { ...@@ -752,8 +727,10 @@ async function delayExcute() {
} }
async function taskpoolExecute() { async function taskpoolExecute() {
taskpool.execute(delayExcute).then((result) => { taskpool.execute(delayExcute).then((result: string) => {
console.log("TaskPoolTest task result: " + result); console.log("taskPoolTest task result: " + result);
}).catch((err: string) => {
console.log("taskpool test occur error: " + err);
}); });
} }
...@@ -765,24 +742,25 @@ taskpoolExecute(); ...@@ -765,24 +742,25 @@ taskpoolExecute();
```ts ```ts
// c.ets // c.ets
@Concurrent @Concurrent
function strSort(inPutArr) { function strSort(inPutArr: Array<string>): Array<string> {
let newArr = inPutArr.sort(); let newArr = inPutArr.sort();
return newArr; return newArr;
} }
export async function func1() { export async function func1() {
console.log("taskpoolTest start"); console.log("taskpoolTest start");
let strArray = ['c test string', 'b test string', 'a test string']; let strArray: Array<string> = ['c test string', 'b test string', 'a test string'];
let task = new taskpool.Task(strSort, strArray); let task: taskpool.Task = new taskpool.Task(strSort, strArray);
let result = await taskpool.execute(task); console.log("func1 result:" + await taskpool.execute(task));
console.log("func1 result:" + result);
} }
export async function func2() { export async function func2() {
console.log("taskpoolTest2 start"); console.log("taskpoolTest2 start");
let strArray = ['c test string', 'b test string', 'a test string']; let strArray: Array<string> = ['c test string', 'b test string', 'a test string'];
taskpool.execute(strSort, strArray).then((result) => { taskpool.execute(strSort, strArray).then((result: Array<string>) => {
console.log("func2 result: " + result); console.log("func2 result: " + result);
}); }).catch((err: string) => {
console.log("taskpool test occur error: " + err);
});
} }
``` ```
...@@ -799,35 +777,35 @@ func2(); ...@@ -799,35 +777,35 @@ func2();
```ts ```ts
// 任务取消成功 // 任务取消成功
@Concurrent @Concurrent
function inspectStatus(arg) { function inspectStatus(arg: number): number {
// 第一时间检查取消并回复 // 第一时间检查取消并回复
if (taskpool.Task.isCanceled()) { if (taskpool.Task.isCanceled()) {
console.log("task has been canceled before 2s sleep."); console.log("task has been canceled before 2s sleep.");
return arg + 2; return arg + 2;
} }
// 2s sleep // 2s sleep
let t = Date.now(); let t: number = Date.now();
while (Date.now() - t < 2000) { while (Date.now() - t < 2000) {
continue; continue;
} }
// 第二次检查取消并作出响应 // 第二次检查取消并作出响应
if (taskpool.Task.isCanceled()) { if (taskpool.Task.isCanceled()) {
console.log("task has been canceled after 2s sleep."); console.log("task has been canceled after 2s sleep.");
return arg + 3; return arg + 3;
} }
return arg + 1; return arg + 1;
} }
async function taskpoolCancel() { async function taskpoolCancel(): Promise<void> {
let task = new taskpool.Task(inspectStatus, 100); // 100: test number let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
taskpool.execute(task).then((res)=>{ taskpool.execute(task).then((res: number)=>{
console.log("taskpool test result: " + res); console.log("taskpool test result: " + res);
}).catch((err) => { }).catch((err: string) => {
console.log("taskpool test occur error: " + err); console.log("taskpool test occur error: " + err);
}); });
// 1s后取消task // 1s后取消task
setTimeout(()=>{ setTimeout(()=>{
taskpool.cancel(task);}, 1000); taskpool.cancel(task);}, 1000);
} }
taskpoolCancel(); taskpoolCancel();
...@@ -838,37 +816,38 @@ taskpoolCancel(); ...@@ -838,37 +816,38 @@ taskpoolCancel();
```ts ```ts
// 已执行的任务取消失败 // 已执行的任务取消失败
@Concurrent @Concurrent
function inspectStatus(arg) { function inspectStatus(arg: number): number {
// 第一时间检查取消并回复 // 第一时间检查取消并回复
if (taskpool.Task.isCanceled()) { if (taskpool.Task.isCanceled()) {
return arg + 2; return arg + 2;
} }
// 延时2s // 延时2s
let t = Date.now(); let t: number = Date.now();
while (Date.now() - t < 2000) { while (Date.now() - t < 500) {
continue; continue;
} }
// 第二次检查取消并作出响应 // 第二次检查取消并作出响应
if (taskpool.Task.isCanceled()) { if (taskpool.Task.isCanceled()) {
return arg + 3; return arg + 3;
} }
return arg + 1; return arg + 1;
} }
async function taskpoolCancel() { async function taskpoolCancel(): Promise<void> {
let task = new taskpool.Task(inspectStatus, 100); // 100: test number let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
taskpool.execute(task).then((res)=>{ taskpool.execute(task).then((res: number)=>{
console.log("taskpool test result: " + res); console.log("taskpool test result: " + res);
}).catch((err) => { }).catch((err: string) => {
console.log("taskpool test occur error: " + err); console.log("taskpool test occur error: " + err);
}); });
setTimeout(()=>{
try { setTimeout(()=>{
taskpool.cancel(task); // 任务已执行,取消失败 try {
} catch (e) { taskpool.cancel(task); // 任务已执行,取消失败
console.log("taskpool.cancel occur error:" + e); } catch (e) {
} console.log("taskpool.cancel occur error:" + e);
}, 3000); // 延时3s,确保任务已执行 }
}, 3000); // 延时3s,确保任务已执行
} }
taskpoolCancel(); taskpoolCancel();
...@@ -879,8 +858,8 @@ taskpoolCancel(); ...@@ -879,8 +858,8 @@ taskpoolCancel();
```ts ```ts
// 待执行的任务组取消成功 // 待执行的任务组取消成功
@Concurrent @Concurrent
function printArgs(args) { function printArgs(args: number): number {
let t = Date.now(); let t: number = Date.now();
while (Date.now() - t < 1000) { while (Date.now() - t < 1000) {
continue; continue;
} }
...@@ -888,26 +867,26 @@ function printArgs(args) { ...@@ -888,26 +867,26 @@ function printArgs(args) {
return args; return args;
} }
async function taskpoolGroupCancelTest() { async function taskpoolGroupCancelTest(): Promise<void> {
let taskGroup1 = new taskpool.TaskGroup(); let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
taskGroup1.addTask(printArgs, 10); // 10: test number taskGroup1.addTask(printArgs, 10); // 10: test number
taskGroup1.addTask(printArgs, 20); // 20: test number taskGroup1.addTask(printArgs, 20); // 20: test number
taskGroup1.addTask(printArgs, 30); // 30: test number taskGroup1.addTask(printArgs, 30); // 30: test number
let taskGroup2 = new taskpool.TaskGroup(); let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
let task1 = new taskpool.Task(printArgs, 100); // 100: test number let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
let task2 = new taskpool.Task(printArgs, 200); // 200: test number let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
let task3 = new taskpool.Task(printArgs, 300); // 300: test number let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number
taskGroup2.addTask(task1); taskGroup2.addTask(task1);
taskGroup2.addTask(task2); taskGroup2.addTask(task2);
taskGroup2.addTask(task3); taskGroup2.addTask(task3);
taskpool.execute(taskGroup1).then((res) => { taskpool.execute(taskGroup1).then((res: Array<number>) => {
console.info("taskpool execute res is:" + res); console.info("taskpool execute res is:" + res);
}).catch((e) => { }).catch((e: string) => {
console.error("taskpool execute error is:" + e); console.error("taskpool execute error is:" + e);
}); });
taskpool.execute(taskGroup2).then((res) => { taskpool.execute(taskGroup2).then((res: Array<number>) => {
console.info("taskpool execute res is:" + res); console.info("taskpool execute res is:" + res);
}).catch((e) => { }).catch((e: string) => {
console.error("taskpool execute error is:" + e); console.error("taskpool execute error is:" + e);
}); });
...@@ -922,48 +901,48 @@ taskpoolGroupCancelTest() ...@@ -922,48 +901,48 @@ taskpoolGroupCancelTest()
```ts ```ts
// 分别创建执行100个高、中、低优先级的任务,查看其各项信息 // 分别创建执行100个高、中、低优先级的任务,查看其各项信息
@Concurrent @Concurrent
function delay() { function delay(): void {
let start = new Date().getTime(); let start: number = new Date().getTime();
while (new Date().getTime() - start < 500) { while (new Date().getTime() - start < 500) {
continue; continue;
} }
} }
let highCount = 0; let highCount: number = 0;
let mediumCount = 0; let mediumCount: number = 0;
let lowCount = 0; let lowCount: number = 0;
let allCount = 100; let allCount: number = 100;
for (let i = 0; i < allCount; i++) { for (let i = 0; i < allCount; i++) {
let task1 = new taskpool.Task(delay); let task1: taskpool.Task = new taskpool.Task(delay);
let task2 = new taskpool.Task(delay); let task2: taskpool.Task = new taskpool.Task(delay);
let task3 = new taskpool.Task(delay); let task3: taskpool.Task = new taskpool.Task(delay);
taskpool.execute(task1, taskpool.Priority.LOW).then(() => { taskpool.execute(task1, taskpool.Priority.LOW).then(() => {
lowCount++; lowCount++;
}).catch((e) => { }).catch((e: string) => {
console.error("low task error: " + e); console.error("low task error: " + e);
}) })
taskpool.execute(task2, taskpool.Priority.MEDIUM).then(() => { taskpool.execute(task2, taskpool.Priority.MEDIUM).then(() => {
mediumCount++; mediumCount++;
}).catch((e) => { }).catch((e: string) => {
console.error("medium task error: " + e); console.error("medium task error: " + e);
}) })
taskpool.execute(task3, taskpool.Priority.HIGH).then(() => { taskpool.execute(task3, taskpool.Priority.HIGH).then(() => {
highCount++; highCount++;
}).catch((e) => { }).catch((e: string) => {
console.error("high task error: " + e); console.error("high task error: " + e);
}) })
} }
let start = new Date().getTime(); let start: number = new Date().getTime();
while (new Date().getTime() - start < 1000) { while (new Date().getTime() - start < 1000) {
continue; continue;
} }
let taskpoolInfo = taskpool.getTaskPoolInfo(); let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo();
let tid = 0; let tid: number = 0;
let taskIds = []; let taskIds: Array<number> = [];
let priority = 0; let priority: number = 0;
let taskId = 0; let taskId: number = 0;
let state = 0; let state: number = 0;
let duration = 0; let duration: number = 0;
for(let threadInfo of taskpoolInfo.threadInfos) { for(let threadInfo of taskpoolInfo.threadInfos) {
tid = threadInfo.tid; tid = threadInfo.tid;
taskIds.length = threadInfo.taskIds.length; taskIds.length = threadInfo.taskIds.length;
......
...@@ -2083,17 +2083,6 @@ Worker基于Actor并发模型实现。在Worker的交互流程中,JS主线程 ...@@ -2083,17 +2083,6 @@ Worker基于Actor并发模型实现。在Worker的交互流程中,JS主线程
Actor并发模型的交互原理:各个Actor并发地处理主线程任务,每个Actor内部都有一个消息队列及单线程执行模块,消息队列负责接收主线程及其他Actor的请求,单线程执行模块则负责串行地处理请求、向其他Actor发送请求以及创建新的Actor。由于Actor采用的是异步方式,各个Actor之间相互隔离没有数据竞争,因此Actor可以高并发运行。 Actor并发模型的交互原理:各个Actor并发地处理主线程任务,每个Actor内部都有一个消息队列及单线程执行模块,消息队列负责接收主线程及其他Actor的请求,单线程执行模块则负责串行地处理请求、向其他Actor发送请求以及创建新的Actor。由于Actor采用的是异步方式,各个Actor之间相互隔离没有数据竞争,因此Actor可以高并发运行。
### 注意事项
- Worker存在数量限制,当前支持最多同时存在8个Worker。
- 在API version 8及之前的版本,当Worker数量超出限制时,会抛出错误Error "Too many workers, the number of workers exceeds the maximum."。
- 从API version 9开始,当Worker数量超出限制时,会抛出错误BusinessError "Worker initialization failure, the number of workers exceeds the maximum."。
- 主动销毁Worker可以调用新创建Worker对象的terminate()或workerPort.close()方法。
- 自API version 9版本开始,若Worker处于已经销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的BusinessError。
- Worker的创建和销毁耗费性能,建议管理已创建的Worker并重复使用。
- 创建Worker工程时,new worker.Worker构造函数和new worker.ThreadWorker构造函数不能同时使用,否则将导致工程中Worker的功能异常。自API version 9版本开始,建议使用[new worker.ThreadWorker](#constructor9)构造函数,在API version 8及之前的版本,建议使用[new worker.Worker](#constructordeprecated)构造函数。
- 创建Worker工程时,在Worker线程的文件中(比如本文中worker.ts)不能导入任何有关构建UI的方法(比如ets文件等),否则会导致Worker的功能失效。排查方式:解压生成的Hap包,在创建Worker线程的文件目录中找到"worker.js",全局搜索"View"关键字。如果存在该关键字,说明在worker.js中打包进去了构建UI的方法,会导致Worker的功能失效,建议在创建Worker线程的文件中修改 "import “xxx” from src"中src的目录层级。
- 线程间通信时传递的数据量最大限制为16M。
## 完整示例 ## 完整示例
> **说明:**<br/> > **说明:**<br/>
> 以API version 9的工程为例。<br> API version 8及之前的版本仅支持FA模型,如需使用,注意更换构造Worker的接口和创建worker线程中与主线程通信的对象的两个方法。 > 以API version 9的工程为例。<br> API version 8及之前的版本仅支持FA模型,如需使用,注意更换构造Worker的接口和创建worker线程中与主线程通信的对象的两个方法。
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册