-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
105 lines (94 loc) · 2.54 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// import { Worker, isMainThread, parentPort } from "worker_threads";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
// let factPromise = (value) =>
// new Promise((resolve, reject) => {
// let startTime = Date.now();
// const worker = new Worker("./fact.js", {
// workerData: {
// value,
// },
// });
// worker.once("message", (data) => {
// let endTime = Date.now();
// resolve(`${endTime - startTime} ms`);
// worker.terminate();
// });
// worker.once("error", (err) => {
// reject(err);
// worker.terminate();
// });
// });
// // main async
// const mainworker = async () => {
// let startTime = Date.now();
// console.log("1");
// console.log(
// await Promise.all([
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// factPromise(10000),
// ])
// );
// console.log("2");
// let endTime = Date.now();
// console.log(`${endTime - startTime} ms`);
// };
// // main();
// mainworker();
import { Worker, isMainThread, parentPort } from "worker_threads";
// Function to calculate factorial (a time-consuming task)
function calculateFactorial(n) {
if (n === 0 || n === 1) return 1;
let result = BigInt(1);
for (let i = 2; i <= n; i++) {
result *= BigInt(i);
}
return result;
}
// Main thread code
console.log("Main thread started.");
const mainStartTime = Date.now();
// Create a worker thread
let factPromise = (value) => {
const worker = new Worker("./fact.js", {
workerData: {
value,
},
});
worker.on("message", (data) => {
console.log(data);
});
};
const value = 1000;
factPromise(value);
// console.log("Main thread posted message to Worker.");