• 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 multi_worker_high_performance_communication]
17import { worker, collections } from '@kit.ArkTS';
18import { BusinessError } from '@kit.BasicServicesKit';
19import { CopyEntry } from './CopyEntry'
20
21function promiseCase() {
22  let p: Promise<void> = new Promise<void>((resolve: Function, reject: Function) => {
23    setTimeout(() => {
24      resolve(1);
25    }, 100)
26  }).then(undefined, (error: BusinessError) => {
27  })
28  return p;
29}
30
31async function postMessageTest() {
32  let ss = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
33  let res = undefined;
34  let flag = false;
35  let isTerminate = false;
36  ss.onexit = () => {
37    isTerminate = true;
38  }
39  // 接收Worker线程发送的消息
40  ss.onmessage = (e) => {
41    res = e.data;
42    flag = true;
43    console.info('worker:: res is  ' + res);
44  }
45  // 给Worker线程发送消息
46  ss.postMessage('hello world');
47  while (!flag) {
48    await promiseCase();
49  }
50
51  ss.terminate();
52  while (!isTerminate) {
53    await promiseCase();
54  }
55}
56
57@Entry
58@Component
59struct Index {
60  @State message: string = 'Hello World';
61
62  build() {
63    Row() {
64      Column() {
65        Text(this.message)
66          .fontSize(50)
67          .fontWeight(FontWeight.Bold)
68          .onClick(() => {
69            postMessageTest();
70            this.message = 'success';
71          })
72      }
73      .width('100%')
74    }
75    .height('100%')
76  }
77}
78// [End multi_worker_high_performance_communication]
79