-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
46 lines (37 loc) · 1.08 KB
/
index.js
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
import { Worker } from 'node:worker_threads'
export const createSimulation = () => {
const state = {
forks: undefined,
philosophers: undefined,
running: false
}
const start = (numberOfPhilosophers = 5) => {
const num = +numberOfPhilosophers
const buffer = new SharedArrayBuffer(num * Int32Array.BYTES_PER_ELEMENT)
state.forks = new Int32Array(buffer)
state.philosophers = Array(num)
.fill(null)
.map((_, philosopher, { length }) => {
const p = new Worker('./philosopher.js', {
workerData: {
philosopher,
// resource hierarchy logic
fork1: philosopher < length - 1 ? philosopher : 0,
fork2: philosopher < length - 1 ? philosopher + 1 : philosopher
}
})
p.postMessage(state.forks)
return p
})
state.running = true
}
const stop = () => {
state.philosophers.forEach(p => p.terminate())
Object.assign(state, {
forks: undefined,
philosophers: undefined,
running: false
})
}
return { stop, start, state }
}