export const raftServer = new raftStateMachine(applyLog)
// const raftStateMachine: raftStateMachine = new raftStateMachine(applyLog)
/**
* Defines the event handler to be called when the worker thread receives a message sent by the host thread.
* The event handler is executed in the worker thread.
*
* @param e message data
*/
workerPort.onmessage = (e: MessageEvents): void => {
raftServer.serve()
}
/**
* Defines the event handler to be called when the worker receives a message that cannot be deserialized.
* The event handler is executed in the worker thread.
*
* @param e message data
*/
workerPort.onmessageerror = (e: MessageEvents): void => {
}
/**
* Defines the event handler to be called when an exception occurs during worker execution.
* The event handler is executed in the worker thread.
*
* @param e error message
*/
workerPort.onerror = (e: ErrorEvent): void => {
}
TimeWorker.ts的代码如下: import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker'; import { CANCEL_TIMER, TIMER_NORMAL_END } from '../utils/ConstData';
const workerPort: ThreadWorkerGlobalScope = worker.workerPort; let isTimerSet: boolean = false /**
* Defines the event handler to be called when the worker thread receives a message sent by the host thread.
* The event handler is executed in the worker thread.
*
* @param e message data
*/
// 接受主线程发来的计时请求,开始启动选举计时器
workerPort.onmessage = function (e: MessageEvents) { let data: number = e.data if (data == CANCEL_TIMER) {
isTimerSet = false } else {
isTimerSet = true setTimeout(()=>{
console.log(data + " ms timeout");
}, data) if (isTimerSet) {
workerPort.postMessage(TIMER_NORMAL_END)
}
}
}
/**
* Defines the event handler to be called when the worker receives a message that cannot be deserialized.
* The event handler is executed in the worker thread.
*
* @param e message data
*/
workerPort.onmessageerror = function (e: MessageEvents) {
console.log(e.data)
}
/**
* Defines the event handler to be called when an exception occurs during worker execution.
* The event handler is executed in the worker thread.
*
* @param e error message
*/
workerPort.onerror = function (e: ErrorEvent) {
console.log(e.message)
}
遇到的问题报错如图:
Device info:OpenHarmony 3.2
Build info:OpenHarmony 4.1.7.7
Fingerprint:e8764f46a043ec63642bc29d819b819e9e65367a3f62f3b62e775d480e17eff1
Module name:com.serise.myapplication
Version:1.0.0
VersionCode:1000000
PreInstalled:No
Foreground:Yes
Pid:2715
Uid:20010044
Reason:TypeError
Error name:TypeError
Error message:Obj is not a Valid object
SourceCode:
workerPort.onmessage = (e: MessageEvents): void => {
^
Stacktrace:
at func_main_0 (entry/src/main/ets/workers/RaftWorker.ets:24:1)