• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import { taskpool } from '@kit.ArkTS';
17import { worker } from '@kit.ArkTS';
18
19const workerInstance: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker1.ts');
20
21let done = false;
22
23// 接收Worker子线程的结果
24workerInstance.onmessage = (() => {
25  console.info('MyWorker.ts onmessage');
26  if (!done) {
27    workerInstance.postMessage({ 'type': 1, 'value': 0 });
28    done = true;
29  }
30})
31
32workerInstance.onerror = (() => {
33  // 接收Worker子线程的错误信息
34})
35
36// 向Worker子线程发送训练消息
37workerInstance.postMessage({ 'type': 0 });
38
39// Worker线程销毁后,执行onexit回调方法
40workerInstance.onexit = (): void => {
41  console.info('main thread terminate');
42}
43
44@Concurrent
45function imageProcessing(dataSlice: ArrayBuffer): ArrayBuffer {
46  // 步骤1: 具体的图像处理操作及其他耗时操作
47  return dataSlice;
48}
49
50function histogramStatistic(pixelBuffer: ArrayBuffer): void {
51  // 步骤2: 分成三段并发调度
52  let number: number = pixelBuffer.byteLength / 3;
53  let buffer1: ArrayBuffer = pixelBuffer.slice(0, number);
54  let buffer2: ArrayBuffer = pixelBuffer.slice(number, number * 2);
55  let buffer3: ArrayBuffer = pixelBuffer.slice(number * 2);
56
57  let group: taskpool.TaskGroup = new taskpool.TaskGroup();
58  group.addTask(imageProcessing, buffer1);
59  group.addTask(imageProcessing, buffer2);
60  group.addTask(imageProcessing, buffer3);
61
62  taskpool.execute(group, taskpool.Priority.HIGH).then((ret: Object) => {
63    // 步骤3: 结果数组汇总处理
64  })
65}
66
67@Entry
68@Component
69struct Index {
70  @State message: string = 'Hello World'
71
72  build() {
73    Row() {
74      Column() {
75        Text(this.message)
76          .fontSize(50)
77          .fontWeight(FontWeight.Bold)
78          .onClick(() => {
79            let buffer: ArrayBuffer = new ArrayBuffer(24);
80            histogramStatistic(buffer);
81            this.message = 'success';
82            // 销毁Worker线程
83            workerInstance.terminate();
84          })
85      }
86      .width('100%')
87    }
88    .height('100%')
89  }
90}