-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfour_index.js
More file actions
42 lines (33 loc) · 1.06 KB
/
four_index.js
File metadata and controls
42 lines (33 loc) · 1.06 KB
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
const express = require('express')
const app = express();
const port = 4000;
const { Worker } = require('worker_threads')
const THREAD_COUNT = 4;
app.get('/non-blocking', (req, res) => {
res.send("this is Non Blocking Response Sent");
})
function createWorker() {
return new Promise((resolve, reject) => {
const worker = new Worker('./four_worker.js', {
workerData: { thread_count: THREAD_COUNT }
})
worker.on("message", (data) => {
resolve(data)
})
worker.on("error", (err) => {
reject(`an error ${err}`)
})
})
}
app.get('/blocking', async (req, res) => {
const workerPromises = [];
for (let i = 0; i < THREAD_COUNT; i++) {
workerPromises.push(createWorker())
}
const thread_results = await Promise.all(workerPromises);
const total = thread_results[0] +thread_results[1]+ thread_results[2] + thread_results[3];
res.status(200).send(`counter result ${total}`);
})
app.listen(port, () => {
console.log("server listening on port=> ", port);
})