-
Notifications
You must be signed in to change notification settings - Fork 1
/
speed-test.thread-worker.ts
58 lines (52 loc) · 1.5 KB
/
speed-test.thread-worker.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { fitness, Gene } from './speed-test.shared'
import { isMainThread, MessagePort, parentPort, Worker } from 'worker_threads'
const { ceil } = Math
const worker_list: Worker[] = []
if (parentPort) {
initWorkerThread(parentPort)
}
export function evalAll(
population: Gene[],
cb: (err: any, score_list: number[]) => void,
) {
if (!isMainThread) {
cb('evalAll() is only available in main thread', [])
return
}
const n_worker = worker_list.length
const score_list: number[] = []
const slice_each_worker = ceil(population.length / n_worker)
let offset = 0
let pending = 0
for (let i = 0; i < n_worker; i++) {
const start = offset
const sub_population = population.slice(start, start + slice_each_worker)
offset += sub_population.length
pending++
worker_list[i].once('message', (sub_score_list: number[]) => {
sub_score_list.forEach((score, i) => {
score_list[start + i] = score
})
pending--
if (pending === 0) {
cb(undefined, score_list)
}
})
worker_list[i].postMessage(sub_population)
}
}
export function initMainThread(n_worker: number) {
for (let i = 0; i < n_worker; i++) {
worker_list[i] = worker_list[i] || new Worker(__filename)
}
}
function initWorkerThread(parentPort: MessagePort) {
parentPort.on('message', message => {
if (message === 'stop') {
process.exit()
}
const gene_list: Gene[] = message
const score_list = gene_list.map(fitness)
parentPort.postMessage(score_list)
})
}