Web workers & worker threads as simple as a function call
npm install @xylabs/threads[![logo][]](https://xylabs.com)
[![main-build][]][main-build-link]
[![npm-badge][]][npm-link]
[![npm-downloads-badge][]][npm-link]
[![jsdelivr-badge][]][jsdelivr-link]
[![npm-license-badge][]](LICENSE)
[![codacy-badge][]][codacy-link]
[![codeclimate-badge][]][codeclimate-link]
[![snyk-badge][]][snyk-link]
[![socket-badge][]][socket-link]
Web workers & worker threads as simple as a function call
@xylabs/threads
*
### functions
*
``ts`
function Transfer(transferable): TransferDescriptor;
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!
Transferable
Array buffer, message port or similar.
`ts`
function Transfer
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!
T
T
Transferable[]
*
`ts`
function isWorkerRuntime(): boolean;
boolean
*
`ts`
function registerSerializer(serializer): void;
SerializerImplementation\<JsonSerializable\>
void
*
`ts`
function spawn
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.
Exposed extends WorkerFunction \| WorkerModule\<any\> = ArbitraryWorkerInterface
Worker
Instance of Worker. Either a web worker, worker_threads worker or tiny-worker worker.
number
Init message timeout. Default: 10000 or set by environment variable.
Promise\<ExposedAs\<Exposed\>\>
### interfaces
*
Thread pool managing a set of worker threads.
Use it to queue tasks that are run on those threads with limited
concurrency.
`ts`
completed(allowResolvingImmediately?): Promise
Returns a promise that resolves once the task queue is emptied.
Promise will be rejected if any task fails.
#### allowResolvingImmediately?
boolean
Set to true to resolve immediately if task queue is currently empty.
Promise\<any\>
*
`ts`
settled(allowResolvingImmediately?): Promise
Returns a promise that resolves once the task queue is emptied.
Failing tasks will not cause the promise to be rejected.
#### allowResolvingImmediately?
boolean
Set to true to resolve immediately if task queue is currently empty.
Promise\<Error[]\>
*
`ts`
events(): Observable
Returns an observable that yields pool events.
Observable\<PoolEvent\<ThreadType\>\>
*
`ts`
queue
Queue a task and return a promise that resolves once the task has been dequeued,
started and finished.
#### Return
Return
#### task
TaskRunFunction\<ThreadType, Return\>
An async function that takes a thread instance and invokes it.
QueuedTask\<ThreadType, Return\>
*
`ts`
terminate(force?): Promise
Terminate all pool threads.
#### force?
boolean
Set to true to kill the thread even if it cannot be stopped gracefully.
Promise\<void\>
*
Task that has been pool.queued()-ed.
Return
`ts`
then:
QueuedTask is thenable, so you can await it.
Resolves when the task has successfully been executed. Rejects if the task fails.
Attaches callbacks for the resolution and/or rejection of the Promise.
#### TResult1
TResult1 = Return
#### TResult2
TResult2 = never
#### onfulfilled?
The callback to execute when the Promise is resolved.
null | (value) => TResult1 \| PromiseLike\<TResult1\>
#### onrejected?
The callback to execute when the Promise is rejected.
null | (reason) => TResult2 \| PromiseLike\<TResult2\>
Promise\<TResult1 \| TResult2\>
A Promise for the completion of which ever callback is executed.
`ts`
cancel(): void;
Queued tasks can be cancelled until the pool starts running them on a worker thread.
void
*
Input = any
`ts`
deserialize(message): Input;
#### message
Msg
Input
*
`ts`
serialize(input): Msg;
#### input
Input
Msg
*
Input = any
`ts`
deserialize(message, defaultDeserialize): Input;
#### message
Msg
#### defaultDeserialize
(msg) => Input
Input
*
`ts`
serialize(input, defaultSerialize): Msg;
#### input
Input
#### defaultSerialize
(inp) => Msg
Msg
*
T = any
`ts`
[$transferable]: true;
*
`ts`
send: T;
*
`ts`
transferables: Transferable[];
### namespaces
### Pool
### type-aliases
*
`ts`
type Event
ThreadType extends Thread = any
*
`ts`
type EventType = PoolEventType;
### type-aliases
*
`ts`
type BlobWorker = typeof BlobWorkerClass;
*
`ts`
type ExposedAs
Exposed extends WorkerFunction \| WorkerModule\<any\>
*
`ts`
type FunctionThread
Args extends any[] = any[]
ReturnType = any
*
`ts`
type JsonSerializable =
| JsonSerializablePrimitive
| JsonSerializablePrimitive[]
| JsonSerializableObject
| JsonSerializableObject[];
*
`ts`
type ModuleThread
Methods extends ModuleMethods = any
*
`ts`
type Thread = ThreadType;
*
`ts`
type Worker = WorkerType;
### variables
*
`ts`
BlobWorker: typeof BlobWorker;
Separate class to spawn workers from source code blobs or strings.
*
`ts`
const DefaultSerializer: Serializer
*
`ts`
Pool:
Thread pool constructor. Creates a new pool and spawns its worker threads.
`ts`
EventType: typeof PoolEventType;
*
`ts`
Thread: object;
Thread utility functions. Use them to manage or inspect a spawn()-ed thread.
`ts`
errors
Return an observable that can be used to subscribe to all errors happening in the thread.
#### ThreadT
ThreadT extends Thread
#### thread
ThreadT
Observable\<Error\>
`ts`
events
Return an observable that can be used to subscribe to internal events happening in the thread. Useful for debugging.
#### ThreadT
ThreadT extends Thread
#### thread
ThreadT
Observable\<WorkerEvent\>
`ts`
terminate
Terminate a thread. Remember to terminate every thread when you are done using it.
#### ThreadT
ThreadT extends Thread
#### thread
ThreadT
Promise\<void\>
*
`ts`
Worker: typeof WorkerImplementation;
Worker implementation. Either web worker or a node.js Worker class.
### functions
*
`ts`
function isWorkerRuntime(): boolean;
boolean
### type-aliases
*
`ts`
type BlobWorker = typeof BlobWorkerClass;
*
`ts`
type Worker = WorkerType;
### variables
*
`ts`
BlobWorker: typeof BlobWorker;
Separate class to spawn workers from source code blobs or strings.
*
`ts``
Worker: typeof WorkerImplementation;
Worker implementation. Either web worker or a node.js Worker class.
Part of sdk-js
- Arie Trouw (arietrouw.com)
- Matt Jones
- Joel Carter
- Jordan Trouw
> See the LICENSE file for license details
[logo]: https://cdn.xy.company/img/brand/XYPersistentCompany_Logo_Icon_Colored.svg
[main-build]: https://github.com/xylabs/sdk-js/actions/workflows/build.yml/badge.svg
[main-build-link]: https://github.com/xylabs/sdk-js/actions/workflows/build.yml
[npm-badge]: https://img.shields.io/npm/v/@xylabs/threads.svg
[npm-link]: https://www.npmjs.com/package/@xylabs/threads
[codacy-badge]: https://app.codacy.com/project/badge/Grade/c8e15e14f37741c18cfb47ac7245c698
[codacy-link]: https://www.codacy.com/gh/xylabs/sdk-js/dashboard?utm_source=github.com&utm_medium=referral&utm_content=xylabs/sdk-js&utm_campaign=Badge_Grade
[codeclimate-badge]: https://api.codeclimate.com/v1/badges/c5eb068f806f0b047ea7/maintainability
[codeclimate-link]: https://codeclimate.com/github/xylabs/sdk-js/maintainability
[snyk-badge]: https://snyk.io/test/github/xylabs/sdk-js/badge.svg?targetFile=package.json
[snyk-link]: https://snyk.io/test/github/xylabs/sdk-js?targetFile=package.json
[npm-downloads-badge]: https://img.shields.io/npm/dw/@xylabs/threads
[npm-license-badge]: https://img.shields.io/npm/l/@xylabs/threads
[jsdelivr-badge]: https://data.jsdelivr.com/v1/package/npm/@xylabs/threads/badge
[jsdelivr-link]: https://www.jsdelivr.com/package/npm/@xylabs/threads
[socket-badge]: https://socket.dev/api/badge/npm/package/@xylabs/threads
[socket-link]: https://socket.dev/npm/package/@xylabs/threads