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 16// [Start process_image_histogram] 17import { taskpool } from '@kit.ArkTS'; 18// [StartExclude process_image_histogram] 19// [Start call_worker_message] 20import { worker } from '@kit.ArkTS'; 21 22const workerInstance: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker1.ts'); 23 24let done = false; 25 26// 接收Worker子线程的结果 27workerInstance.onmessage = (() => { 28 console.info('MyWorker.ts onmessage'); 29 if (!done) { 30 workerInstance.postMessage({ 'type': 1, 'value': 0 }); 31 done = true; 32 } 33}) 34 35workerInstance.onerror = (() => { 36 // 接收Worker子线程的错误信息 37}) 38 39// 向Worker子线程发送训练消息 40workerInstance.postMessage({ 'type': 0 }); 41// [End call_worker_message] 42 43// [Start after_destroy_callback] 44// Worker线程销毁后,执行onexit回调方法 45workerInstance.onexit = (): void => { 46 console.info('main thread terminate'); 47} 48// [End after_destroy_callback] 49// [EndExclude process_image_histogram] 50 51@Concurrent 52function imageProcessing(dataSlice: ArrayBuffer): ArrayBuffer { 53 // 步骤1: 具体的图像处理操作及其他耗时操作 54 return dataSlice; 55} 56 57function histogramStatistic(pixelBuffer: ArrayBuffer): void { 58 // 步骤2: 分成三段并发调度 59 let number: number = pixelBuffer.byteLength / 3; 60 let buffer1: ArrayBuffer = pixelBuffer.slice(0, number); 61 let buffer2: ArrayBuffer = pixelBuffer.slice(number, number * 2); 62 let buffer3: ArrayBuffer = pixelBuffer.slice(number * 2); 63 64 let group: taskpool.TaskGroup = new taskpool.TaskGroup(); 65 group.addTask(imageProcessing, buffer1); 66 group.addTask(imageProcessing, buffer2); 67 group.addTask(imageProcessing, buffer3); 68 69 taskpool.execute(group, taskpool.Priority.HIGH).then((ret: Object) => { 70 // 步骤3: 结果数组汇总处理 71 }) 72} 73 74@Entry 75@Component 76struct Index { 77 @State message: string = 'Hello World' 78 79 build() { 80 Row() { 81 Column() { 82 Text(this.message) 83 .fontSize(50) 84 .fontWeight(FontWeight.Bold) 85 .onClick(() => { 86 let buffer: ArrayBuffer = new ArrayBuffer(24); 87 histogramStatistic(buffer); 88 this.message = 'success'; 89 // 销毁Worker线程 90 workerInstance.terminate(); 91 }) 92 } 93 .width('100%') 94 } 95 .height('100%') 96 } 97} 98// [End process_image_histogram]