-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsideThread.js
31 lines (28 loc) · 906 Bytes
/
sideThread.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
const { isMainThread, parentPort, workerData, threadId, MessageChannel, MessagePort, Worker } = require("worker_threads")
function mainThread() {
const worker = new Worker(__filename, { workerData: 0 })
worker.on("exit", code => {
console.log(`main: worker stopped with exit code ${code}`)
})
worker.on("message", msg => {
console.log(`main: receive ${msg}`)
worker.postMessage(msg + 1)
})
}
function workerThread() {
console.log(`worker: __________ threadId ${threadId} start with ${__filename}`)
console.log(`worker: workerDate -> ${workerData}`)
parentPort.on("message", msg => {
console.log(`worker: receive ${msg}`)
if (msg === 5) {
process.exit()
}
parentPort.postMessage(msg)
}),
parentPort.postMessage(workerData)
}
if (isMainThread) {
mainThread()
} else {
workerThread()
}