nanothreads icon indicating copy to clipboard operation
nanothreads copied to clipboard

document how to use functions & imported stuff from InlineThreads

Open CodeF53 opened this issue 1 year ago • 1 comments

People will want to be able to use functions from outside the context of an inlineThread

import { InlineThread } from 'nanothreads'
import _ from 'lodash'

export function randomQuestion(): string {
  return _.sample(['how are you', 'aaa', 'bbb', 'ccc'])
}

const inlineThread = new InlineThread<[name: string], string>((name) => {
  return `hello ${name}! ${randomQuestion()}`
}, {})

console.log(await inlineThread.send('AAA'))

but it doesn't work

$ bun test.ts
200 |   #onClose(e) {
201 |     this.#onExitPromise = e.code, this.emit("exit", e.code);
202 |   }
203 |   #onError(event) {
204 |     let error = event?.error;
205 |       error = new Error(event.message, { cause: event });
                    ^
error: 1 | const H=async(...a)=>((name) => {
2 |   return `hello ${name}! ${randomQuestion()}`;
                               ^
ReferenceError: Can't find variable: randomQuestion
      at blob:006c7714-3aae-4b3c-bf05-7e71803f3848:2:28
      at H (blob:006c7714-3aae-4b3c-bf05-7e71803f3848:1:18)
      at blob:006c7714-3aae-4b3c-bf05-7e71803f3848:3:25

 cause: {
  "isTrusted": true
}

CodeF53 avatar Dec 07 '24 05:12 CodeF53

I achieved a horrid way of doing this with concurrent.js with

/**
 * Creates a threaded version of a given function.
 * @param {Function} func - The original function to be executed on another thread.
 * @param {string} funcFile - The file path or URL of the module containing the original function. `import.meta.url` in most cases
 */
export function asThreaded<I extends any[], O>(func: (...args: I) => O, funcFile: string): (...args: I) => Promise<O> {
  concurrent.config({ maxThreads: availableParallelism() })
  const concurrentThis = concurrent.import(funcFile)

  return async function (...args: I): Promise<O> {
    return ((await concurrentThis.load() as Record<string, Function>)[func.name])(...args) as Promise<O>
  }
}
export function toBeThreaded(...): ... {
  ...
}
const threadedFunc = asThreaded(obstructionTest, import.meta.url)

but I was hoping I could use this library to dodge that nonsense

CodeF53 avatar Dec 07 '24 05:12 CodeF53