Skip to content

Commit

Permalink
fix: recycleWorkers to destroy idle workers when runtime changes (#75)
Browse files Browse the repository at this point in the history
  • Loading branch information
AriPerkkio committed Nov 5, 2023
1 parent 999778e commit e79c650
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1071,12 +1071,16 @@ class ThreadPool {
}

async recycleWorkers(options: Pick<Options, 'runtime'> = {}) {
const runtimeChanged =
options?.runtime && options.runtime !== this.options.runtime

if (options?.runtime) {
this.options.runtime = options.runtime
}

// Worker's are automatically recycled when isolateWorkers is enabled
if (this.options.isolateWorkers) {
// Worker's are automatically recycled when isolateWorkers is enabled.
// Idle workers still need to be recycled if runtime changed
if (this.options.isolateWorkers && !runtimeChanged) {
return
}

Expand Down
20 changes: 20 additions & 0 deletions test/runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,26 @@ test('runtime can be changed after recycle', async () => {
})
})

test('isolated idle workers change runtime after recycle', async () => {
const pool = createPool({
runtime: 'worker_threads',
minThreads: 2,
maxThreads: 2,
isolateWorkers: true,
})
const getState = 'process.__tinypool_state__'

await expect(pool.run(getState)).resolves.toMatchObject({
isWorkerThread: true,
})

await pool.recycleWorkers({ runtime: 'child_process' })

await expect(
Promise.all([pool.run(getState), pool.run(getState)])
).resolves.toMatchObject([{ isChildProcess: true }, { isChildProcess: true }])
})

function createPool(options: Partial<Tinypool['options']>) {
const pool = new Tinypool({
filename: path.resolve(__dirname, 'fixtures/eval.js'),
Expand Down

0 comments on commit e79c650

Please sign in to comment.