Working multithreading...

This commit is contained in:
BurnyLlama 2021-10-13 19:45:59 +02:00
parent 747ef0acf9
commit 36ecb5c6a7
4 changed files with 80 additions and 48 deletions

View File

@ -10,27 +10,28 @@ export function initWorkers(threads) {
for (const i in workerFarm) {
const worker = workerFarm[i]
worker.postMessage({
type: 'setName',
type: 'initWorker',
name: `Worker ${parseInt(i) + 1}`
})
}
}
export function spread(threads, script, data, shouldEval) {
return new Promise((resolve, reject) => {
const worker = new Worker(
let spreadIndex = 0
export function spread(script, data) {
return new Promise(
(resolve, reject) => {
const worker = workerFarm[spreadIndex]
worker.postMessage({
type: 'runScript',
script,
{
workerData: data,
eval: shouldEval ?? false
data
})
worker.once('message', result => resolve(result))
++spreadIndex
if(spreadIndex >= workerFarm.length)
spreadIndex = 0
}
)
worker.on('message', resolve)
worker.on('error', reject)
worker.on('exit', (code) => {
if (code !== 0)
reject(new Error(`Process stopped with code: ${code}`))
})
})
}

View File

@ -1,8 +1,13 @@
import { workerData, parentPort } from 'worker_threads'
import initLog from '../log.js'
const log = initLog('Fibonacci')
export function main(data) {
return new Promise(
(resolve, reject) => {
let nums = [1, 1]
for (let i = 0; i < 42; i++) {
for (let i = 0; i < 44; i++) {
nums.push(nums[nums.length - 2] + nums[nums.length - 1])
}
@ -18,6 +23,7 @@ for (const num of nums) {
primes.push(num)
}
console.log("DONE!")
parentPort.postMessage(primes)
resolve(primes)
}
)
}

View File

@ -1,30 +1,37 @@
import { workerData, parentPort } from 'worker_threads'
import initLog from '../log.js'
let script = ''
let runScript = ''
let myName = ''
let log = initLog(myName)
parentPort.on(
'message',
message => {
async message => {
switch (message.type) {
case 'setName':
case 'initWorker':
myName = message.name
log = initLog(myName)
log(`Changed name to '${myName}'.`)
process.env.DEBUG && log(`Started new thread -> «${myName}»`)
break
case 'setScript':
script = message.script
log = initLog(myName)
log(`Changed name to '${myName}'.`)
break
case 'runScript':
runScript = message.script
process.env.DEBUG && log(`Running script -> «${runScript}»`)
import(runScript).then(
script => script.main(message.data).then(
result => {
parentPort.postMessage(result)
process.env.DEBUG && log(`Script done -> «${runScript}»`)
}
)
)
break
default:
log(`Invalid message -> ${message.type ?? 'No message type provided!'}`)
break
}
}

View File

@ -1,3 +1,21 @@
import { initWorkers, spread } from '../libs/utils/multithread.js'
initWorkers(8)
initWorkers(10)
let processes = 20
let ran = 0
for (let i = 0; i < processes; ++i) {
spread(
'./fibonacci.js',
{}
).then(
result => {
console.log(i)
++ran
if (ran === processes) {
process.exit(0)
}
}
)
}