Skip to content

Mutual callable worker thread pool with fallback. Based on okie.

License

Notifications You must be signed in to change notification settings

sapphi-red/artichokie

Folders and files

NameName
Last commit message
Last commit date
Dec 17, 2024
Dec 17, 2024
Dec 17, 2024
Sep 2, 2024
Nov 7, 2023
Nov 6, 2023
Nov 6, 2023
Dec 13, 2024
Sep 2, 2024
Mar 2, 2025
Mar 2, 2025
Nov 7, 2023
Nov 6, 2023
Dec 17, 2024
Dec 17, 2024

Repository files navigation

artichokie

npm version CI MIT License

Okie dokie artichokie

Mutual callable worker thread pool with fallback. Based on okie.

Features

  • worker pool
  • calling functions in the main thread from the worker
  • falling back to run the code in the main thread

Examples

const parent = async () => 1
const syncParent = () => 2
const worker = new Worker(
  () => async () => {
    return (await parent()) + syncParent() + 1
  },
  {
    parentFunctions: { parent, syncParent }
  }
)

const result = await worker.run()
console.log(result) // 4

worker.stop()
const infSymbol = Symbol('inf')
const isInf = async (n: number | symbol) => n === infSymbol

const worker = new WorkerWithFallback(
  () => async (n: number | symbol) => {
    return await isInf(n) ? Infinity : 0
  },
  {
    parentFunctions: { isInf },
    shouldUseFake(n) {
      // symbol cannot be passed to a worker
      // fallback to run the code in main thread in that case
      return typeof n === 'symbol'
    }
  }
)

const results = await Promise.all([
  worker.run(1),
  worker.run(infSymbol)
])

console.log(results) // [0, Infinity]

worker.stop()