Skip to content

worker_threads: worker handles not cleaned up in async_hooks API #26535

Description

@chjj
  • Version: v11.10.1
  • Platform: Linux 4.20.11-arch1-1-ARCH deps: update openssl to 1.0.1j #1 SMP PREEMPT Wed Feb 20 21:11:12 UTC 2019 x86_64 GNU/Linux
  • Subsystem: worker_threads

Not sure if it's a bug or not, but I've noticed that destroy is never executed for the asyncIds pertaining to workers.

'use strict';

const threads = require('worker_threads');

if (!threads.isMainThread) {
  console.log('Thread: ' + threads.threadId);
  return;
}

const hooks = require('async_hooks');

async function spawn(file) {
  const worker = new threads.Worker(file);
  return new Promise((resolve, reject) => {
    worker.on('exit', resolve);
  });
}

async function wait(ms) {
  return new Promise(cb => setTimeout(cb, ms));
}

(async () => {
  const active = new Map();

  const hook = hooks.createHook({
    init(id, type) {
      if (type === 'WORKER')
        active.set(id, type);
    },
    destroy(id) {
      active.delete(id);
    }
  });

  hook.enable();

  for (let i = 0; i < 10; i++)
    await spawn(__filename);

  await wait(1000);

  hook.disable();

  await wait(1000);

  console.log(active);
})();

Output:

Thread: 1
Thread: 2
Thread: 3
Thread: 4
Thread: 5
Thread: 6
Thread: 7
Thread: 8
Thread: 9
Thread: 10
Map {
  3 => 'WORKER',
  23 => 'WORKER',
  39 => 'WORKER',
  55 => 'WORKER',
  71 => 'WORKER',
  87 => 'WORKER',
  103 => 'WORKER',
  119 => 'WORKER',
  135 => 'WORKER',
  151 => 'WORKER' }

Activity

  1. added
    workerIssues and PRs related to the worker_threads module and Worker API.
    on Mar 9, 2019
  2. addaleax commented on Mar 9, 2019

    @addaleax
    Member

    I don’t think it’s quite a bug, because it’s only happening because the destroy() hook for Workers currently relies on garbage collection (like for many other objects); the Worker object itself owns no resources anymore when it is collected.

    However, this is still fixable in the sense that we can destroy the objects earlier, if we want: #26542

  3. chjj commented on Mar 9, 2019

    @chjj
    ContributorAuthor

    Ahh, I see. No worries then. I was just concerned the handles were not being cleaned up or something.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    workerIssues and PRs related to the worker_threads module and Worker API.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions