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