• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2const common = require('../common');
3if (common.isIBMi)
4  common.skip('On IBMi, the rss memory always returns zero');
5
6const assert = require('assert');
7const util = require('util');
8const { Worker } = require('worker_threads');
9
10let numWorkers = +process.env.JOBS || require('os').availableParallelism();
11if (numWorkers > 20) {
12  // Cap the number of workers at 20 (as an even divisor of 60 used as
13  // the total number of workers started) otherwise the test fails on
14  // machines with high core counts.
15  numWorkers = 20;
16}
17
18// Verify that a Worker's memory isn't kept in memory after the thread finishes.
19
20function run(n, done) {
21  console.log(`run() called with n=${n} (numWorkers=${numWorkers})`);
22  if (n <= 0)
23    return done();
24  const worker = new Worker(
25    'require(\'worker_threads\').parentPort.postMessage(2 + 2)',
26    { eval: true });
27  worker.on('message', common.mustCall((value) => {
28    assert.strictEqual(value, 4);
29  }));
30  worker.on('exit', common.mustCall(() => {
31    run(n - 1, done);
32  }));
33}
34
35const startStats = process.memoryUsage();
36let finished = 0;
37for (let i = 0; i < numWorkers; ++i) {
38  run(60 / numWorkers, () => {
39    console.log(`done() called (finished=${finished})`);
40    if (++finished === numWorkers) {
41      const finishStats = process.memoryUsage();
42      // A typical value for this ratio would be ~1.15.
43      // 5 as a upper limit is generous, but the main point is that we
44      // don't have the memory of 50 Isolates/Node.js environments just lying
45      // around somewhere.
46      assert.ok(finishStats.rss / startStats.rss < 5,
47                'Unexpected memory overhead: ' +
48                util.inspect([startStats, finishStats]));
49    }
50  });
51}
52