-
Notifications
You must be signed in to change notification settings - Fork 0
/
mpmt1.js
95 lines (81 loc) · 2.28 KB
/
mpmt1.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
// mpmt1.js: A Node.js version of mpmt1.py
//
//License:
// Apache License, Version 2.0
//History:
// * 2021/12/30 v0.1 Initial version
//Author:
// Masanori Itoh <[email protected]>
//TODO:
// * Implement async mode(?)
function busy_worker(timeout) {
// ts and ts_save are in mili-seconds
var ts_save = Date.now()
// duration is in seconds.
var max = timeout * 1000
while (true) {
ts = Date.now()
if ((ts - ts_save) >= max) {
console.log('Expired! ' + (ts - ts_save))
break
}
}
if (mode == 'p') {
process.exit(0)
}
}
var posix_getopt = require('posix-getopt')
var parser, option
const cluster = require('cluster')
var num_context = 4
var duration = 10
var mode = 'p'
parser = new posix_getopt.BasicParser('n:d:m:', process.argv)
while ((option = parser.getopt()) !== undefined) {
switch (option.option) {
case 'n':
num_context = option.optarg
break;
case 'd':
duration = option.optarg
break;
case 'm':
mode = option.optarg
break;
}
}
if (mode == 'p') {
//Process mode (cluster)
if (cluster.isMaster) {
console.log('num_context: ' + num_context + ' duration: ' + duration + ' mode: ' + mode)
console.log('parent: pid= ' + process.pid)
for (var i = 0; i < num_context; i++) {
cluster.fork()
}
cluster.on('exit', (code, signal) => {
// signal is the value for process.exit()? node code?
console.log('on exit called. code= ' + code + ' signal= ' + signal)
});
} else {
console.log('child: pid=' + process.pid)
busy_worker(duration)
}
} else {
//Thread mode (worker_thread)
const {
Worker,
isMainThread,
//parentPort,
} = require("worker_threads");
if (isMainThread) {
console.log('num_context: ' + num_context + ' duration: ' + duration + ' mode: ' + mode)
const threads = [];
for (var i = 0; i < num_context; i++) {
const worker = new Worker(__filename, {argv: process.argv.slice(2)});
threads.push(worker)
}
//TODO(thatsdone): Implement join() equivalent for synchronization
} else {
busy_worker(duration)
}
}