Added worker pools, and very very basic workers

This commit is contained in:
mrfry 2020-12-18 21:32:43 +01:00
parent 771959ec2b
commit f5f3b51eee
5 changed files with 211 additions and 5 deletions

View file

@ -598,11 +598,58 @@ const workerTs = (file: string, wkOpts: any) => {
)
}
if (!isMainThread) {
logger.DebugLog(`Starting search worker ...`, 'searchworker', 1)
const { data, subjName, question, questionData } = workerData
searchWorker(data, subjName, question, questionData)
// if (!isMainThread) {
// logger.DebugLog(`Starting search worker ...`, 'searchworker', 1)
// const { data, subjName, question, questionData } = workerData
// searchWorker(data, subjName, question, questionData)
// }
function random(min, max) {
return Math.floor(Math.random() * (max - min) + min)
}
if (!isMainThread) {
const workerIndex = workerData.workerIndex
const timeoutMin = workerData.workerTimeoutMin
const timeoutMax = workerData.workerTimeoutMax
const data = { val: 0 }
console.log(
`[THREAD #${workerIndex}]: Worker ${workerIndex} reporting for duty`
)
console.log(`[THREAD #${workerIndex}]: data`, workerData)
// parentPort.postMessage('hello parent port')
parentPort.on('message', (msg) => {
// console.log(`[THREAD #${workerIndex}]: onmsg`, msg)
if (msg.type === 'work') {
const index = msg.index
console.log(`[THREAD #${workerIndex}]: staring work on ${index}`)
setTimeout(() => {
data.val = data.val + msg.add
parentPort.postMessage({
msg: `From thread #${workerIndex}: job ${index} done`,
workerIndex: workerIndex,
result: data.val,
})
console.log(`[THREAD #${workerIndex}]: Work ${index} done!`)
}, random(timeoutMin, timeoutMax))
} else if (msg.type === 'update') {
if (msg.data.workerIndex !== workerIndex) {
console.log(`[THREAD #${workerIndex}]: update`, msg.data)
console.log(
`[THREAD #${workerIndex}]: From ${data.val} to ${msg.data.result}`
)
data.val = msg.data.result
}
}
})
} else {
console.log('[THREAD]: Main thread!')
}
// ------------------------------------------------------------------------
export {