11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ci
31cb0ef41Sopenharmony_ciconst common = require('../common');
41cb0ef41Sopenharmony_ciconst assert = require('assert');
51cb0ef41Sopenharmony_ciconst fs = require('fs/promises');
61cb0ef41Sopenharmony_ciconst { scheduler } = require('timers/promises');
71cb0ef41Sopenharmony_ciconst { parentPort, Worker } = require('worker_threads');
81cb0ef41Sopenharmony_ci
91cb0ef41Sopenharmony_ciconst MAX_ITERATIONS = 5;
101cb0ef41Sopenharmony_ciconst MAX_THREADS = 6;
111cb0ef41Sopenharmony_ci
121cb0ef41Sopenharmony_ci// Do not use isMainThread so that this test itself can be run inside a Worker.
131cb0ef41Sopenharmony_ciif (!process.env.HAS_STARTED_WORKER) {
141cb0ef41Sopenharmony_ci  process.env.HAS_STARTED_WORKER = 1;
151cb0ef41Sopenharmony_ci
161cb0ef41Sopenharmony_ci  function spinWorker(iter) {
171cb0ef41Sopenharmony_ci    const w = new Worker(__filename);
181cb0ef41Sopenharmony_ci    w.on('message', common.mustCall((msg) => {
191cb0ef41Sopenharmony_ci      assert.strictEqual(msg, 'terminate');
201cb0ef41Sopenharmony_ci      w.terminate();
211cb0ef41Sopenharmony_ci    }));
221cb0ef41Sopenharmony_ci
231cb0ef41Sopenharmony_ci    w.on('exit', common.mustCall(() => {
241cb0ef41Sopenharmony_ci      if (iter < MAX_ITERATIONS)
251cb0ef41Sopenharmony_ci        spinWorker(++iter);
261cb0ef41Sopenharmony_ci    }));
271cb0ef41Sopenharmony_ci  }
281cb0ef41Sopenharmony_ci
291cb0ef41Sopenharmony_ci  for (let i = 0; i < MAX_THREADS; i++) {
301cb0ef41Sopenharmony_ci    spinWorker(0);
311cb0ef41Sopenharmony_ci  }
321cb0ef41Sopenharmony_ci} else {
331cb0ef41Sopenharmony_ci  async function open_close() {
341cb0ef41Sopenharmony_ci    const fh = await fs.open(__filename);
351cb0ef41Sopenharmony_ci    await fh.close();
361cb0ef41Sopenharmony_ci    await scheduler.yield();
371cb0ef41Sopenharmony_ci    await open_close();
381cb0ef41Sopenharmony_ci  }
391cb0ef41Sopenharmony_ci
401cb0ef41Sopenharmony_ci  // These async function calls never return as they are meant to continually
411cb0ef41Sopenharmony_ci  // open and close files until the worker is terminated.
421cb0ef41Sopenharmony_ci  open_close();
431cb0ef41Sopenharmony_ci  open_close();
441cb0ef41Sopenharmony_ci
451cb0ef41Sopenharmony_ci  parentPort.postMessage('terminate');
461cb0ef41Sopenharmony_ci}
47