-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread.ts
More file actions
47 lines (40 loc) · 1.6 KB
/
thread.ts
File metadata and controls
47 lines (40 loc) · 1.6 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
43
44
45
46
47
/* eslint-disable @typescript-eslint/no-require-imports */
// index.ts
require("dotenv").config();
import { Worker, isMainThread, threadId } from "worker_threads";
import path from "path";
import { MashServer } from "./backend";
const port = Number(process.env.NEXT_PUBLIC_BACKEND_PORT) || 4000;
const threads = Number(process.env.NEXT_PUBLIC_BACKEND_THREADS) || 2;
if (isMainThread) {
const acceptorApp = new MashServer();
acceptorApp.listen(port, (): void => {
console.log(`Main Thread: listening on port ${port} (thread ${threadId})`);
});
// Spawn worker threads with incremental ports
const cpuCount = require("os").cpus().length;
if (threads > cpuCount) {
console.warn(
`WARNING: Number of threads (${threads}) is greater than the number of CPUs (${cpuCount})`
);
}
const usableThreads = Math.min(threads, cpuCount);
for (let i = 0; i < usableThreads; i++) {
const worker = new Worker(path.resolve(__dirname, "backend", "worker.ts"), {
execArgv: ["-r", "ts-node/register", "-r", "module-alias/register"], // Add module-alias/register here
workerData: { port: 4001 + i }, // Unique port for each worker
});
// Listen for messages and errors from the worker
worker.on("message", (workerAppDescriptor) => {
acceptorApp.addChildAppDescriptor(workerAppDescriptor);
});
worker.on("error", (err) => {
console.error(`Error in worker ${i}:`, err);
});
worker.on("exit", (code) => {
if (code !== 0) {
console.error(`Worker ${i} stopped with exit code ${code}`);
}
});
}
}