• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2* Copyright (C) 2025 HiHope Open Source Organization.
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*/
15import { ErrorEvent, MessageEvents, taskpool, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
16import { task } from '../ConcurrencyModularImportTaskTest';
17
18const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
19
20export async function sleep(time: number): Promise<number> {
21  return new Promise<number>((resolve): void => {
22    setTimeout((): void => {
23      resolve(1);
24    }, time);
25  });
26}
27
28/**
29 * Defines the event handler to be called when the worker thread receives a message sent by the host thread.
30 * The event handler is executed in the worker thread.
31 *
32 * @param event message data
33 */
34workerPort.onmessage = async (event: MessageEvents) => {
35  let str: number = event.data;
36  console.log('str:' + str);
37  if (str === 1) {
38    try {
39      throw new Error('error in then worker.');
40    } catch (e) {
41      workerPort.postMessage({ error: e.message });
42    }
43  }
44  if (str === 2) {
45    let count: string = '0';
46    let workThread1: worker.ThreadWorker;
47    workThread1 = new worker.ThreadWorker('../workers/ImportWorker2');
48    workThread1.onexit = () => {
49      console.log('onexit2');
50    }
51    workThread1.postMessage('1');
52    workThread1.onmessage = async (e: MessageEvents): Promise<void> => {
53      count = e.data;
54      workThread1.terminate();
55    }
56    while (count != '1') {
57      await sleep(300)
58    }
59    workerPort.postMessage(count);
60  }
61  if (str === 3) {
62    await taskpool.execute(task).catch((e: Error) => {
63      workerPort.postMessage(42);
64    })
65    workerPort.close();
66  }
67};
68/**
69 * Defines the event handler to be called when the worker receives a message that cannot be deserialized.
70 * The event handler is executed in the worker thread.
71 *
72 * @param event message data
73 */
74workerPort.onmessageerror = (event: MessageEvents) => {
75};
76
77/**
78 * Defines the event handler to be called when an exception occurs during worker execution.
79 * The event handler is executed in the worker thread.
80 *
81 * @param event error message
82 */
83workerPort.onerror = (event: ErrorEvent) => {
84};