{"id":22709499,"url":"https://github.com/mstephen19/threadz","last_synced_at":"2025-04-13T13:33:13.404Z","repository":{"id":37023931,"uuid":"495343914","full_name":"mstephen19/threadz","owner":"mstephen19","description":"A feature rich and scalable general-purpose multi-threading library that makes it easy to utilize all of a given machine's resources in Node.js.","archived":false,"fork":false,"pushed_at":"2022-12-01T00:25:59.000Z","size":286,"stargazers_count":9,"open_issues_count":1,"forks_count":1,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-03-27T04:34:12.457Z","etag":null,"topics":["javascript","multithreading","nodejs","thread","threads","typescript","worker-pool","worker-threads","workers"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/threadz","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mstephen19.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-05-23T09:35:14.000Z","updated_at":"2023-04-05T15:29:09.000Z","dependencies_parsed_at":"2023-01-23T19:30:49.079Z","dependency_job_id":null,"html_url":"https://github.com/mstephen19/threadz","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mstephen19%2Fthreadz","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mstephen19%2Fthreadz/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mstephen19%2Fthreadz/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mstephen19%2Fthreadz/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mstephen19","download_url":"https://codeload.github.com/mstephen19/threadz/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248721560,"owners_count":21151118,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["javascript","multithreading","nodejs","thread","threads","typescript","worker-pool","worker-threads","workers"],"created_at":"2024-12-10T11:09:58.195Z","updated_at":"2025-04-13T13:33:13.376Z","avatar_url":"https://github.com/mstephen19.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Threadz\n\n## !!! THIS PACKAGE HAS BEEN DEPRECATED\n\nThreadz will no longer be maintained. Please use [Nanolith](https://github.com/mstephen19/nanolith) instead for multi-threading in Node.js. It is stable and maintained regularly.\n\n\u003e Threadz now supports ESModules!\n\n![npm](https://img.shields.io/npm/v/threadz) [![MIT](https://img.shields.io/badge/license-MIT-blue)](https://github.com/mstephen19/threadz/blob/main/LICENSE) ![npm](https://img.shields.io/npm/dw/threadz)\n\n![TypeScript](https://badgen.net/badge/-/TypeScript/blue?icon=typescript\u0026label) [![CircleCI](https://circleci.com/gh/mstephen19/threadz.svg?style=svg)](https://app.circleci.com/pipelines/github/mstephen19/threadz) [![GitHub issues](https://img.shields.io/github/issues/mstephen19/threadz)](https://github.com/mstephen19/threadz/issues)\n\n![Logo](https://i.imgur.com/L7158yF.jpg)\n\nA feature rich and scalable general-purpose multi-threading library that makes it easy to utilize all of a given machine's resources in Node.js.\n\n## New in v2.3.x\n\n- New [`BackgroundThreadzWorker`](#backgroundthreadzworker) API.\n- Various bug fixes.\n- Minor improvements to the [`SharedMemory`](#sharedmemory) API.\n- Support for both ESModules and CommonJS.\n- Minor bug fixes \u0026 edge case handling.\n- [`waitForStart`](#waitforstart) method on `ThreadzWorker`.\n\n## Table of Contents\n\n- [Features](#features)\n- [Installing](#installing)\n- [Example](#example)\n- [`declare`](#declare)\n- [ThreadzAPI](#threadzapi)\n- [`merge`](#merge)\n- [`Interact` API](#interact-api)\n- [`Communicate` API](#communicate-api)\n- [`ThreadzWorker`](#threadzworker)\n- [`BackgroundThreadzWorker`](#backgroundthreadzworker)\n- [ThreadzPool](#threadzpool)\n- [workerTools](#workertools)\n- [`SharedMemory`](#sharedmemory)\n\n## Features\n\n- Full TypeScript support + in-editor documentation with JSDoc.\n- Create modular workers without having to create specific worker files.\n- Run operations with true concurrency by using workers in your code as if they were just regular functions that return promises.\n- Automatically manage worker concurrency.\n- Intuitively share memory between workers.\n- Prioritize certain workers over others.\n- Receive descriptive error messages that tell you exactly what you've done wrong.\n\n## Installing\n\nThreadz is currently only available on NPM.\n\n```shell\nnpm i threadz\n```\n\n## Example\n\n**declarations.ts:**\n\n```TypeScript\nimport { declare } from 'threadz';\n\nexport default declare({\n    bigLoop: {\n        worker: (num: number) =\u003e {\n            // Normally, a for loop is blocking code\n            for (const _ of Array(900000000).keys()) {\n            }\n            return num + 100;\n        },\n    },\n});\n```\n\n**index.ts:**\n\n```TypeScript\nimport api from './declarations';\n\n// Run the for loop on a separate thread\nconst data = await api.workers.bigLoop(5);\nconsole.log(data);\n\nconsole.log('this will run before the data is logged');\n```\n\n## `declare`\n\n`(declarations: Declarations)` =\u003e [`ThreadzAPI`](#threadzapi)\n\nRegardless of how you plan on using Threadz, the place you'll always need to start is the `declare()` function. Pass in a map of declarations where each key pertains to the name under which you'd like the function to be recognized.\n\n```TypeScript\n// declarations.ts\nimport { declare } from 'threadz';\n\nexport default declare({\n    // The name of the worker\n    helloWorld: {\n        // The function to be run when the worker is called.\n        worker: () =\u003e console.log('hello world'),\n\n        // Whether or not to push the worker to the front of\n        // the ThreadzPool queue when it is added.\n        // Defaults to \"false\".\n        priority: true,\n\n        // Default options for the \"Worker\" class from the\n        // \"worker_threadz\" module.\n        options: {\n            resourceLimits: {\n                maxOldGenerationSizeMb: 0.5,\n            },\n        },\n    },\n    logMessage: {\n        // The \"worker\" property is the only one required.\n        worker: (msg: string) =\u003e console.log(msg),\n    },\n    returnSum: {\n        worker: (num1: number, num2: number) =\u003e num1 + num2\n    }\n});\n```\n\nDeclaration functions can also be asynchronous and return promises, which will be awaited within the worker. The function under the **worker** property doesn't have to be defined right within the `declare()` function. It can be imported from elsewhere.\n\nTo get a full list of the configurations supported in the **options** property, refer to the [Node.js documentation](https://nodejs.org/api/worker_threads.html#new-workerfilename-options).\n\n\u003e **Note:** Threadz will do its best to detect the path of the declaration file, but sometimes it might fail. In rare cases like these, you can manually pass a `fileLocation` string within the second parameter.\n\u003e **Note:** The return value of the `declare()` function **MUST** be the default export of the file.\n\u003e **Note:** Unfortunately, declaration functions cannot accept generic types.\n\n## ThreadzAPI\n\nThe `declare()` function returns an instance of `ThreadzAPI`, off of which your workers can be called. During initialization, declaration functions are mapped into the `threadzAPI.workers` property, where they can be referenced by the names used in the original declarations. Using the declarations in the above section, this code would be valid:\n\n```TypeScript\n// index.ts\nimport api from './declarations';\n\n// Each of these operations is happening on a separate thread\nawait api.workers.logMessage('threadz is awesome');\nawait api.workers.helloWorld();\n\n// The return value of a worker function is a promise of\n// the return value of the original declaration function\n// it corresponds to.\nconst data = await api.workers.returnSum(4, 5)\n\nconsole.log(data) // -\u003e 9\n```\n\n### Methods \u0026 properties\n\n- **`location`**: _`string`_\n  - The file location at which the declarations live.\n  - Tells Threadz how to dynamically import your declarations.\n- **`declarations`**: _[`Declarations`](#declare)_\n  - The original declarations used to initialize `ThreadsAPI`.\n- **`declarationsCount`**: _`number`_\n  - The number of declarations on the `ThreadzAPI` instance.\n- **`workers`**: _`MappedWorkers`_\n  - Declarations mapped into \"worker functions\" which handle the passing of data, the creation of `Worker` instances, the management of worker concurrency with ThreadzPool, and more.\n- **`threadzPool`**: _[`ThreadzWorkerPool`](#threadzpool)_\n  - The global `ThreadzWorkerPool` instance being used to manage all workers.\n- **`interactWith()`**: _`(workerName: string)` =\u003e [`Interact`](#interact-api)_\n  - Pass in the name of a worker on the `ThreadzAPI` instance to create an interaction session for that worker with the `Interact` API.\n- **`createBackgroundWorker()`**: _`({ options?: WorkerOptions })` =\u003e [`BackgroundThreadzWorker`](#backgroundthreadzworker)_\n- **`on()`**: `(callback: Function)` =\u003e `void`\n  - Supports the `workerQueued` and `workerDone` methods.\n\n## `merge`\n\n`(instances: ThreadzAPI[])` =\u003e `Declarations`\n\nThe `merge` function is a simple function that accepts an array of ThreadzAPI instances returned by the `declare` function and returns a new declarations object containing all declarations from each instance provided in the array.\n\n\u003e **Note:** `merge` does **not** return a ThreadzAPI instance like `declare!` It returns a set of declarations to be re-declared.\n\n**Example:**\n\n**declarations.ts**\n\n```TypeScript\nimport { declare, merge } from 'threadz';\n\nconst math = declare({\n    add5: {\n        worker: (num1: number) =\u003e num1 + 5,\n    },\n});\n\nconst logging = declare({\n    helloWorld: {\n        worker: () =\u003e 'hello world',\n    },\n});\n\nexport default declare(merge([math, logging]));\n```\n\n**index.ts**\n\n```TypeScript\nimport api from './declarations';\n\nawait api.workers.add5(5);\nawait api.workers.helloWorld();\n```\n\n\u003e **Note:** if you are only using the `declare` function to create a ThreadzAPI instance with the sole intention of using it later in the `merge` function to be re-declared, it does not have to be the default export of the file it is in.\n\n## `Interact` API\n\nDirectly calling workers on `threadzAPI.workers` allows for the ability to pass arguments to a function, run it on a separate thread, then receive its return value back on the main thread. For any workflows more complex than this, the `Interact` API must be used.\n\nInitialize an interaction session with the `Interact.with()` static method, passing in a worker function from a `ThreadzAPI` instance. An `Interact` instance tied to that worker function will be returned.\n\n```TypeScript\nimport { Interact } from 'threadz';\nimport api from './declarations';\n\n// Initialize the interact session, specifying which worker\n// to run the interaction with.\nconst interact = Interact.with(api.workers.returnSum);\n\n// Pass in arguments to the worker and mark it as a priority.\ninteract.args(4, 5).isPriority();\n\n// Run callbacks when certain worker events have occurred.\ninteract.onStart(() =\u003e console.log('Worker started'));\ninteract.onSuccess((result) =\u003e console.log(result));\n\n// Queue the worker into the ThreadzPool and run it.\nconst worker = interact.go();\n\n// Wait for the worker to finish running\nawait worker.waitFor();\n```\n\n### Methods\n\nAn instance of the `Interact` API has many methods that make it easy to interact with a worker, all of which can be chained.\n\n#### `args()`\n\nPass arguments into the worker.\n\n#### `isPriority()`\n\nThis means that it will be pushed to the front of the [ThreadzPool](#threadzpool) queue instead of the back. Overrides the **priority** option set in the original declarations.\n\n#### `isNotPriority()`\n\nTreat the worker as normal. You only need to use this method if you set `priority` to `true` in the original declaration.\n\n#### `setOptions()`\n\n`(options: WorkerOptions)` =\u003e `Interact`\n\nSet the options for the worker's run. Overrides any options defined within the original declaration.\n\n#### `setOptionsWithPrevious()`\n\n`(callback: (options: WorkerOptions) =\u003e WorkerOptions)` =\u003e `Interact`\n\nSet the options for the worker's run with a callback. Overrides any options defined within the original declaration.\n\n#### `addMessagePort()`\n\n\u003e This function is documented and readily available; however it is recommended to use the [`Communicate`](#communicate-api) API instead.\n\n`(port: MessagePort)` =\u003e `Interact`\n\nAdd a message port to the worker to be accessed by [`workerTools.sendCommunication`](#workertools) and `workerTools.onCommunication`.\n\n**Example:**\n\n```TypeScript\nimport { MessageChannel } from 'worker_threads';\nimport api from './declarations';\n\nconst { port1, port2 } = new MessageChannel();\n\nconst worker = api.interactWith('test').addMessagePort(port2).go();\n\nport1.on('message', (data) =\u003e console.log(data));\n\nawait worker.waitFor();\n```\n\n#### `go()`\n\n`()` =\u003e [`ThreadzWorker`](#threadzworker)\n\nCreate the worker and queue it up in the ThreadzPool to be run. Returns a `ThreadzWorker` instance.\n\n#### Events\n\n- **`onMessage()`**\n  - Pass a function to run when a message is received from the worker.\n- **`onFailure()`**\n  - Pass a function to run when the worker fails and throws an error.\n- **`onSuccess()`**\n  - Pass a function to run when the worker succeeds and potentially returns a value.\n- **`onStart()`**\n  - Pass a function to run when the worker starts running.\n  - This functionality might be useful when dealing with large queues of workers.\n- **`onAbort()`**\n  - Pass a function to run whenever the worker is aborted.\n  - A worker can only be aborted with the [`workerTools.abort()`](#workertools) and `workerTools.abortOnTimeout()` functions.\n\n## `Communicate` API\n\nThe `Communicate` class is a simple class that acts as a Threadz-specific wrapper for the [`MessageChannel` class](https://nodejs.org/api/worker_threads.html#class-messagechannel) from the `worker_threads` module in Node.js. Pass in [`Interact`](#interact-api) instances and automatically create a `MessageChannel` instance and add the ports to the `Interact` instances with `interact.addMessagePort()`\n\n```TypeScript\nimport { Communicate } from 'threadz';\nimport api from './declarations';\n\nconst add5 = api.interactWith('add5').args(10);\nconst helloWorld = api.interactWith('helloWorld');\n\nconst communicate = Communicate.between([add5, helloWorld]);\n\nadd5.go();\nhelloWorld.go();\n\ncommunicate.on('message', (data) =\u003e console.log(data));\n\ncommunicate.closePorts();\n```\n\nIn the `between` static method, you can either pass in a tuple of two `Interact` instances, or an object with `port1` and `port2` keys, each containing an array of `Interact` instances. The instances under each key will automatically be passed the corresponding port.\n\n```TypeScript\n// Instead of this\nconst { port1, port2 } = new MessageChannel();\nadd5.addMessagePort(port1);\nhelloWorld.addMessagePort(port2);\n\n// Communicate allows you to do this instead\nconst communicate = Communicate.between([add5, helloWorld]);\n```\n\nThis becomes more useful when trying to create communications between a larger number of workers.\n\n## `ThreadzWorker`\n\nWhen a `ThreadzWorker` instance is returned by the [`Interact` API](#interact-api), it represents a worker that has been queued into the [`ThreadzWorkerPool`](#threadzpool) to be executed.\n\n```TypeScript\nimport { Interact } from 'threadz';\nimport api from './declarations';\n\nconst interact = Interact.with(api.workers.returnSum).args(4, 5);\nconst worker = interact.go();\n\nworker.sendMessage('foo');\n```\n\n\u003e **Note:** Other than with the `Interact` API, you should not be directly working with `ThreadzWorker` instances.\n\n### Methods \u0026 properties\n\nSince the `ThreadzWorker` API is not meant to be interacted with extensively, a limited number of methods are available.\n\n#### `isRunning`\n\nA boolean indicating whether or not the worker is running yet.\n\n#### `sendMessage()`\n\n`(data: AcceptableDataType | SharedMemoryTransferObject, transferList?: TransferListItem[])` =\u003e `void`\n\nSend a message to the worker while it is running by passing in a basic data type or a [`SharedMemoryTransferObject`](#sharedmemory).\n\n#### `setPriority()`\n\n`(priority: boolean | 0 | 1)` =\u003e `void`\n\nSets the priority of the worker based on a boolean or number value. Has no effect if the worker is already running.\n\n#### `waitForStart()`\n\n`()` =\u003e `Promise\u003cvoid\u003e`\n\nAllows you to wait for the worker to start before trying to interact with it while it's running.\n\n#### `waitFor()`\n\n`()` =\u003e `Promise`\n\nReturns a promise which resolves/rejects once the worker has succeeded, thrown an error, or aborted.\n\nThe data the promise resolves with is the return value of the original declaration function.\n\n#### `justWaitFor()`\n\n`()` =\u003e `Promise\u003cvoid\u003e`\n\nReturns a promise that will always resolve when the worker finishes, regardless of whether it succeeded, errored out, or was aborted.\n\n#### `on()`\n\n`(callback: Function)` =\u003e `void`\n\nSupports the `message`, `error`, `aborted`, `success`, and `started` events.\n\n#### `ref()`, `unref()`, and `terminate()`\n\nRefer to the [Node.js documentation](https://nodejs.org/api/worker_threads.html#workerunref) for more details.\n\n## `BackgroundThreadzWorker`\n\nThis class cannot be directly interacted with, but can be instantiated via the [`createBackgroundWorker`](#threadzapi) function on a `ThreadzAPI` instance. Background workers work differently from regular workers, as they begin running when you call the `start()` function, and only finish when you call `end()`.\n\nNormal `ThreadzWorker`s spin up a [`Worker`](https://nodejs.org/api/worker_threads.html#class-worker) for a single function call, then finish once the function has returned (or resolved with) some value. `BackgroundThreadzWorker`s allow you to spin up only one worker, then have access to calling any of your declared worker functions without needing to spin up a new `Worker` each time.\n\n```TypeScript\n// declarations.ts\nimport { declare, workerTools } from 'threadz';\n\nexport default declare({\n    add: {\n        worker: (num1: number, num2: number) =\u003e num1 + num2,\n    },\n    subtract: {\n        worker: (num1: number, num2: number) =\u003e num1 - num2,\n    },\n});\n```\n\n```TypeScript\n// index.ts\nimport api from './declarations.js';\n\nconst backgroundWorker = api.createBackgroundWorker();\n\n// Spins up a single worker\nawait backgroundWorker.start();\n\nconst result = await backgroundWorker.call('add', 1, 2);\n\n// The \"subtract\" worker function is being run on the same thread\n// as the call for \"add\"\nconst result2 = await backgroundWorker.call('subtract', 5, 3);\n\n// Ends the worker's process\nbackgroundWorker.end();\n\nconsole.log(result, result2);\n```\n\nThough the output is the same, the functionality above is very different from this:\n\n```TypeScript\n// index.ts\nimport api from './declarations.js';\n\n// Spins up a new Worker, runs the add function.\n// The worker's process is ended once the add function returns.\nconst result = await api.workers.add(1, 2);\n\n// Spins up a new Worker, runs the subtract function.\n// The worker's process is ended once the subtract function returns.\nconst result2 = await api.workers.subtract(5, 3);\n\nconsole.log(result, result2);\n```\n\n### Methods \u0026 properties\n\n#### `start()`\n\n`(port?: MessagePort)` =\u003e `Promise\u003cvoid\u003e`\n\nStarts the background worker. You can optionally pass a `MessagePort` object to enable the usage of methods such as [`workerTools.onCommunication`](#workertools) within the worker.\n\n#### `call()`\n\n`(name: string, ...args: unknown[])` =\u003e `Promise\u003cunknown\u003e`\n\nCalls the declaration function, applying the arguments passed to it. Returns a promise of the declaration function's return type.\n\n#### `end()`\n\n`()` =\u003e `void`\n\nEnds the worker's process.\n\n#### ``\n\n## ThreadzPool\n\nThe `ThreadzWorkerPool` (importable under the name `ThreadzPool`) is a single global object which implements a queuing system to manage workers and maintain a maximum concurrency.\n\n### Methods \u0026 properties\n\nThe methods and properties on `ThreadzWorkerPool` make it easy to modify its maximum concurrency and get updates on its status.\n\n#### `queueLength`\n\nGet the current length of the queue.\n\n#### `maxedOut`\n\nWhether or not the max number of possible workers is running right now.\n\n#### `currentlyActive`\n\nThe number of workers which are currently running.\n\n#### `maxConcurrency`\n\nThe maximum number of workers that ThreadzWorkerPool will allow to run concurrently.\n\n#### `setMaxConcurrency()`\n\n`(value: MaxConcurrencyOptions | number` =\u003e `void`\n\nSet the maximum concurrency of the ThreadzPool by either specifying how many workers you'd like to run at once with a number, or a `MaxConcurrencyOptions` (importable enum) value which dynamically calculates the max concurrency based on the resources the machine has.\n\n**`MaxConcurrencyOptions`:**\n\n- `1/4`\n- `1/2`\n- `3/4`\n- `100%`\n- `200%`\n- `400%`\n\n\u003e **Note:** It is recommended to use `MaxConcurrencyOptions` instead of a hardset number.\n\n#### `nextUp`\n\nRetrieve the name, location, and arguments of the next worker in the queue to be run.\n\n#### `dormant`\n\nIf `true`, the ThreadzWorkerPool is not currently running any workers and the queue is empty.\n\n#### `on()`\n\n`(callback: Function)` =\u003e `void`\n\nSupports the `dormant` event.\n\n## workerTools\n\nThe `workerTools` object is a set of tools intended for use exclusively within workers. It can be used to send and receive messages to and from the main thread, as well as communicate with other workers running on different threads.\n\n```TypeScript\nimport { declare, workerTools } from 'threadz';\n\nexport default declare({\n    myWorker: {\n        worker: () =\u003e {\n            workerTools.onParentMessage((data) =\u003e {\n                console.log(data);\n            });\n\n            workerTools.sendMessageToParent('hey!');\n\n            workerTools.abort();\n        },\n    },\n});\n```\n\n### Methods \u0026 properties\n\nThere are currently 7 tools in the `workerTools` toolbox.\n\n#### `sendMessageToParent()`\n\n`(data: AcceptableDataType | SharedMemoryTransferObject, transferList?: TransferListItem[])` =\u003e `void`\n\nSend a message to be consumed back on the main thread.\n\n#### `onParentMessage()`\n\n`(callback: Function)` =\u003e `Function`\n\nPass a function to run any time a message is received from the parent thread. The data is passed in as the first parameter.\n\nReturns a function that stops listening on the parent port when called.\n\n#### `waitForParentMessage()`\n\nA function which takes in an assertion callback. The assertion callback takes in the received data and returns a boolean value. If the assertion returns `true`, the promise will resolve.\n\n#### `sendCommunication()`\n\n`(data: AcceptableDataType | SharedMemoryTransferObject, transferList?: TransferListItem[])` =\u003e `void`\n\nIf you have passed a message port to the worker (using the [`Interact` API](#interact-api)), send messages to the port with this function.\n\n#### `onCommunication()`\n\n`(callback: Function)` =\u003e `Function`\n\nIf you have passed a message port to the worker (using the Interact API), listen for messages on the port with this function by passing a callback which takes in the received data.\n\nReturns a function that stops listening on the port when called.\n\n#### `waitForCommunication()`\n\nA function which takes in an assertion callback. The assertion callback takes in the received data and returns a boolean value. If the assertion returns `true`, the promise will resolve.\n\n#### `threadID()`\n\nGrab the unique ID of the thread currently being used.\n\n#### `abort()`\n\n`(message?: string)` =\u003e `never`\n\nImmediately terminate the worker and return out with an `aborted` status.\n\n#### `abortOnTimeout()`\n\n`({ seconds, message }: { seconds: number, message: string })` =\u003e `never`\n\nPrevent workers from hanging or running too long by aborting out after a certain amount of time has passed.\n\n## `SharedMemory`\n\nSharing memory between multiple threads is simple with the Threadz `SharedMemory` API. Use the static `SharedMemory.from()` method to create a shared state which is retained on all threads.\n\n```TypeScript\nimport { SharedMemory } from 'threadz';\n\nconst mem = SharedMemory.from\u003cRecord\u003cstring, string\u003e\u003e({ foo: 'bar' });\n\nconsole.log(mem.get()); // -\u003e { foo: 'bar' };\n\nmem.setWith((prev) =\u003e {\n    return {\n        ...prev,\n        fizz: 'buzz',\n    };\n});\n\nconsole.log(mem.get());\n```\n\n### Methods \u0026 properties\n\nThere are a few different properties and methods on a `SharedMemory` instance to help you manipulate the data stored within its state, as well as send it to other threads.\n\n#### `byteLength`\n\nThe byte length of the stored Uint8Array.\n\n#### `transfer()`\n\n`()` =\u003e `SharedMemoryTransferObject`\n\nThis is one of the most important methods on the `SharedMemory` API. Instances cannot be directly send to workers via parameters or messages, so they must be converted into `SharedMemoryTransferObjects`s using the `sharedMemory.transfer()` function.\n\n**Example:**\n\n**declarations.ts**:\n\n```TypeScript\nimport { declare, SharedMemory } from 'threadz';\nimport type { SharedMemoryTransferObject } from 'threadz';\n\nexport default declare({\n    myWorker: {\n        // The memory data will come in as a SharedMemoryTransferObject\n        worker: (transfer: SharedMemoryTransferObject\u003cstring\u003e) =\u003e {\n            // We can use the SharedMemory.from() function on a\n            // SharedMemoryTransferObject and continue using the\n            // SharedMemory API to manipulate the data.\n            const mem = SharedMemory.from(transfer);\n\n            console.log(mem.get());\n        },\n    },\n});\n```\n\n**index.ts**:\n\n```TypeScript\nimport { SharedMemory } from 'threadz';\nimport api from './declarations';\n\nconst mem = SharedMemory.from('hey');\n\n// The SharedMemory instance must be converted into a\n// SharedMemoryTransferObject when passed into a worker\nawait api.workers.myWorker(mem.transfer());\n```\n\n#### `get()`\n\n`(microtask?: boolean)` =\u003e `unknown`\n\nGet the current state.\n\nPass in `true` to run the operation as a microtask (returns a promise).\n\n#### `wipe()`\n\n`(microtask?: boolean)` =\u003e `void`\n\nEntirely reset the memory space (not deletion of the memory space!).\n\nPass in `true` to run the operation as a microtask (returns a promise).\n\n#### `set()`\n\n`(data: AcceptableDataType)` =\u003e `void`\n\nSet a new value for the current memory space.\n\nPass in `true` to run the operation as a microtask (returns a promise).\n\n#### `setWith()`\n\n`(callback: (data: AcceptableDataType) =\u003e AcceptableDataType)` =\u003e `void`\n\nSet a new state with a callback function taking in the previous data and returning the new data to be written to memory.\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmstephen19%2Fthreadz","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmstephen19%2Fthreadz","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmstephen19%2Fthreadz/lists"}