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 { ArkTSUtils, ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS'; 16import { numberPromise } from '../ConcurrencyModularImportPromiseTest'; 17 18// import { numberPromise } from 'library1'; 19 20const workerPort: ThreadWorkerGlobalScope = worker.workerPort; 21 22/** 23 * Defines the event handler to be called when the worker thread receives a message sent by the host thread. 24 * The event handler is executed in the worker thread. 25 * 26 * @param event message data 27 */ 28workerPort.onmessage = async (event: MessageEvents) => { 29 if (event.data === '1') { 30 workerPort.postMessage(event.data); 31 } else if (event.data === '2') { 32 let s: string[] = []; 33 s[0].split('')[1].toString(); 34 workerPort.postMessage(event.data); 35 } 36 if (event.data === '3') { 37 setTimeout(async () => { 38 await workerPort.postMessage(event.data); 39 }, 100); 40 } 41 if (event.data === 1) { 42 const numberResult = await numberPromise; 43 console.log('String result:', numberResult); 44 workerPort.postMessage(numberResult); 45 workerPort.close(); 46 } 47 if (event.data === 2) { 48 let lock1: ArkTSUtils.locks.AsyncLock = ArkTSUtils.locks.AsyncLock.request('lock_1'); 49 await lock1.lockAsync(async () => { 50 await workerPort.postMessage(42); 51 console.info('Lock section executed'); 52 }, ArkTSUtils.locks.AsyncLockMode.EXCLUSIVE); 53 workerPort.close(); 54 } 55}; 56 57 58/** 59 * Defines the event handler to be called when the worker receives a message that cannot be deserialized. 60 * The event handler is executed in the worker thread. 61 * 62 * @param event message data 63 */ 64workerPort.onmessageerror = (event: MessageEvents) => { 65}; 66 67/** 68 * Defines the event handler to be called when an exception occurs during worker execution. 69 * The event handler is executed in the worker thread. 70 * 71 * @param event error message 72 */ 73workerPort.onerror = (event: ErrorEvent) => { 74};