threads

  • Version 1.7.0
  • Published
  • 178 kB
  • 5 dependencies
  • MIT license

Install

npm i threads
yarn add threads
pnpm add threads

Overview

Web workers & worker threads as simple as a function call

Index

Variables

variable BlobWorker

const BlobWorker: typeof BlobWorkerClass;
  • Separate class to spawn workers from source code blobs or strings.

variable DefaultSerializer

const DefaultSerializer: Serializer<JsonSerializable, any>;

    variable isWorkerRuntime

    const isWorkerRuntime: () => boolean;
    • Returns true if this code is currently running in a worker.

    variable Pool

    const Pool: (<ThreadType extends Thread>(
    spawnWorker: () => Promise<ThreadType>,
    optionsOrSize?: number | PoolOptions
    ) => WorkerPool<ThreadType>) & { EventType: typeof PoolEventType };
    • Thread pool constructor. Creates a new pool and spawns its worker threads.

    variable Thread

    const Thread: {
    errors<ThreadT extends ThreadType>(thread: ThreadT): Observable<Error>;
    events<ThreadT_1 extends ThreadType>(thread: ThreadT_1): Observable<WorkerEvent>;
    terminate<ThreadT_2 extends ThreadType>(thread: ThreadT_2): Promise<void>;
    };
    • Thread utility functions. Use them to manage or inspect a spawn()-ed thread.

    variable Worker

    const Worker: typeof WorkerImplementation;
    • Worker implementation. Either web worker or a node.js Worker class.

    Functions

    function expose

    expose: (exposed: WorkerFunction | WorkerModule<any>) => void;
    • Expose a function or a module (an object whose values are functions) to the main thread. Must be called exactly once in every worker thread to signal its API to the main thread.

      Parameter exposed

      Function or object whose values are functions

    function registerSerializer

    registerSerializer: (
    serializer: SerializerImplementation<JsonSerializable>
    ) => void;

      function spawn

      spawn: <
      Exposed extends WorkerFunction | WorkerModule<any> = ArbitraryWorkerInterface
      >(
      worker: WorkerType,
      options?: { timeout?: number }
      ) => Promise<ExposedToThreadType<Exposed>>;
      • Spawn a new thread. Takes a fresh worker instance, wraps it in a thin abstraction layer to provide the transparent API and verifies that the worker has initialized successfully.

        Parameter worker

        Instance of Worker. Either a web worker, worker_threads worker or tiny-worker worker.

        Parameter options

        Parameter

        [options.timeout] Init message timeout. Default: 10000 or set by environment variable.

      function Transfer

      Transfer: {
      (transferable: Transferable): TransferDescriptor;
      <T>(payload: T, transferables: Transferable[]): TransferDescriptor<any>;
      };
      • Mark a transferable object as such, so it will no be serialized and deserialized on messaging with the main thread, but to transfer ownership of it to the receiving thread.

        Only works with array buffers, message ports and few more special types of objects, but it's much faster than serializing and deserializing them.

        Note: The transferable object cannot be accessed by this thread again unless the receiving thread transfers it back again!

        Parameter transferable

        Array buffer, message port or similar.

        See Also

        • <https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast>

      • Mark transferable objects within an arbitrary object or array as being a transferable object. They will then not be serialized and deserialized on messaging with the main thread, but ownership of them will be tranferred to the receiving thread.

        Only array buffers, message ports and few more special types of objects can be transferred, but it's much faster than serializing and deserializing them.

        Note: The transferable object cannot be accessed by this thread again unless the receiving thread transfers it back again!

        Parameter transferable

        Array buffer, message port or similar.

        See Also

        • <https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast>

      Interfaces

      interface Pool

      interface Pool<ThreadType extends Thread> {}
      • Thread pool managing a set of worker threads. Use it to queue tasks that are run on those threads with limited concurrency.

      method completed

      completed: (allowResolvingImmediately?: boolean) => Promise<any>;
      • Returns a promise that resolves once the task queue is emptied. Promise will be rejected if any task fails.

        Parameter allowResolvingImmediately

        Set to true to resolve immediately if task queue is currently empty.

      method events

      events: () => Observable<PoolEvent<ThreadType>>;
      • Returns an observable that yields pool events.

      method queue

      queue: <Return>(
      task: TaskRunFunction<ThreadType, Return>
      ) => QueuedTask<ThreadType, Return>;
      • Queue a task and return a promise that resolves once the task has been dequeued, started and finished.

        Parameter task

        An async function that takes a thread instance and invokes it.

      method settled

      settled: (allowResolvingImmediately?: boolean) => Promise<Error[]>;
      • Returns a promise that resolves once the task queue is emptied. Failing tasks will not cause the promise to be rejected.

        Parameter allowResolvingImmediately

        Set to true to resolve immediately if task queue is currently empty.

      method terminate

      terminate: (force?: boolean) => Promise<void>;
      • Terminate all pool threads.

        Parameter force

        Set to true to kill the thread even if it cannot be stopped gracefully.

      interface Serializer

      interface Serializer<Msg = JsonSerializable, Input = any> {}

        method deserialize

        deserialize: (message: Msg) => Input;

          method serialize

          serialize: (input: Input) => Msg;

            interface SerializerImplementation

            interface SerializerImplementation<Msg = JsonSerializable, Input = any> {}

              method deserialize

              deserialize: (message: Msg, defaultDeserialize: (msg: Msg) => Input) => Input;

                method serialize

                serialize: (input: Input, defaultSerialize: (inp: Input) => Msg) => Msg;

                  interface TransferDescriptor

                  interface TransferDescriptor<T = any> {}

                    property [$transferable]

                    [$transferable]: true;

                      property send

                      send: T;

                        property transferables

                        transferables: Transferable[];

                          Type Aliases

                          type BlobWorker

                          type BlobWorker = typeof BlobWorkerClass;

                            type FunctionThread

                            type FunctionThread<
                            Args extends any[] = any[],
                            ReturnType = any
                            > = ProxyableFunction<Args, ReturnType> & PrivateThreadProps;

                              type JsonSerializable

                              type JsonSerializable =
                              | JsonSerializablePrimitive
                              | JsonSerializablePrimitive[]
                              | JsonSerializableObject
                              | JsonSerializableObject[];

                                type ModuleThread

                                type ModuleThread<Methods extends ModuleMethods = any> = ModuleProxy<Methods> &
                                PrivateThreadProps;

                                  type Thread

                                  type Thread = ThreadType;

                                    type Worker

                                    type Worker = WorkerType;

                                      Namespaces

                                      namespace Pool

                                      namespace Pool {}

                                        type Event

                                        type Event<ThreadType extends Thread = any> = PoolEvent<ThreadType>;

                                          type EventType

                                          type EventType = PoolEventType;

                                            Package Files (11)

                                            Dependencies (5)

                                            Dev Dependencies (28)

                                            Peer Dependencies (0)

                                            No peer dependencies.

                                            Badge

                                            To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                            You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/threads.

                                            • Markdown
                                              [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/threads)
                                            • HTML
                                              <a href="https://www.jsdocs.io/package/threads"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>