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 { worker, ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@kit.ArkTS'; 17 18let workerPort: ThreadWorkerGlobalScope = worker.workerPort; 19 20// 定义训练模型及结果 21let result: Array<number>; 22 23// 定义预测函数 24function predict(x: number): number { 25 return result[x]; 26} 27 28// 定义优化器训练过程 29function optimize(): void { 30 result = [0]; 31} 32 33// Worker线程的onmessage逻辑 34workerPort.onmessage = (e: MessageEvents): void => { 35 // 根据传输的数据的type选择进行操作 36 switch (e.data.type as number) { 37 case 0: 38 // 进行训练 39 optimize(); 40 // 训练之后发送宿主线程训练成功的消息 41 workerPort.postMessage({ type: 'message', value: 'train success.' }); 42 break; 43 case 1: 44 // 执行预测 45 const output: number = predict(e.data.value as number); 46 // 发送宿主线程预测的结果 47 workerPort.postMessage({ type: 'predict', value: output }); 48 break; 49 default: 50 workerPort.postMessage({ type: 'message', value: 'send message is invalid' }); 51 break; 52 } 53 // 销毁线程 54 // workerPort.close(); 55}