Skip to content

Commit

Permalink
feat: allow fractions to define thread limits. eg minThreads: 0.5 use…
Browse files Browse the repository at this point in the history
…s 50% of available cores
  • Loading branch information
dominikg authored and Aslemammad committed Jul 16, 2022
1 parent d7bd76c commit 64c0f3e
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ interface FilledOptions extends Options {
const kDefaultOptions: FilledOptions = {
filename: null,
name: 'default',
minThreads: Math.max(cpuCount / 2, 1),
minThreads: 0.5,
maxThreads: cpuCount,
idleTimeout: 0,
maxQueue: Infinity,
Expand Down Expand Up @@ -972,6 +972,28 @@ class Tinypool extends EventEmitterAsyncResource {
#pool: ThreadPool

constructor(options: Options = {}) {
// convert fractional option values to int
if (
options.minThreads !== undefined &&
options.minThreads > 0 &&
options.minThreads < 1
) {
options.minThreads = Math.max(
1,
Math.floor(options.minThreads * cpuCount)
)
}
if (
options.maxThreads !== undefined &&
options.maxThreads > 0 &&
options.maxThreads < 1
) {
options.maxThreads = Math.max(
1,
Math.floor(options.maxThreads * cpuCount)
)
}

super({ ...options, name: 'Tinypool' })

if (
Expand Down
50 changes: 50 additions & 0 deletions test/options.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import Tinypool from 'tinypool'
import { cpus } from 'os'
const cpuCount = cpus().length

const testIf = (condition) => (condition ? test : test.skip)

describe('options', () => {
// TODO mock amount instead?
testIf(cpuCount > 1)('fractional thread limits can be set', async () => {
const min = 0.5
const max = 0.75
const p = new Tinypool({
minThreads: min,
maxThreads: max,
})

expect(p.options.minThreads).toBe(Math.floor(cpuCount * min))
expect(p.options.maxThreads).toBe(Math.floor(cpuCount * max))
})

test('fractional thread limits result is 1 for very low fractions', async () => {
const min = 0.00005
const max = 0.00006
const p = new Tinypool({
minThreads: min,
maxThreads: max,
})

expect(p.options.minThreads).toBe(1)
expect(p.options.maxThreads).toBe(1)
})

testIf(cpuCount > 2)(
'fractional thread limits in the wrong order throw an error',
async () => {
expect(() => {
new Tinypool({
minThreads: 0.75,
maxThreads: 0.25,
})
}).toThrow()
expect(() => {
new Tinypool({
minThreads: 0.75,
maxThreads: 1,
})
}).toThrow()
}
)
})

0 comments on commit 64c0f3e

Please sign in to comment.