thread-tasks
Version:
Thread Tasks: Offload your CPU-intensive tasks to separate threads.
48 lines (45 loc) • 2.19 kB
text/typescript
import { Worker } from 'worker_threads';
type Task<TaskArguments> = {
fn: (data: TaskArguments) => any | ((data: TaskArguments) => Promise<any>);
args?: TaskArguments;
onSuccess?: (msg: any) => any;
onError?: (err: Error) => any;
};
/**
* Runs the given tasks in parallel threads, allowing for CPU-intensive operations
* to be offloaded from the main thread. Each task is given its own worker, and
* the tasks are run in the order they are given in the array. The function
* returns an array of Worker objects, which can be used to terminate the
* workers if needed.
*
* @param tasks An array of tasks to run in parallel. Each task is an object with
* three properties: `fn` (a function that takes no arguments), `args` (an
* optional object that is passed to the worker as `workerData`), and
* `onSuccess` and `onError` (optional functions that are called with the
* result of the task if it succeeds or fails, respectively).
*
* @returns An array of Worker objects, which can be used to terminate the
* workers if needed.
*/
declare function threadTasks<TaskArguments>(tasks: Task<TaskArguments>[]): Promise<Worker>[];
/**
* Executes a set of tasks in parallel threads, with controlled concurrency (max thread count).
*
* @param tasks - An array of tasks to run in parallel. Each task is an object
* with the following properties: `fn` (a function to be executed), `args`
* (optional arguments for the function), and optional `onSuccess` and
* `onError` callbacks.
* @param getMaxThreads - An optional function that returns the maximum
* number of simultaneously running tasks allowed. If not provided, it defaults to
* the number of CPU cores available.
* @param afterAll - An optional callback function that is executed after all
* tasks have been completed.
*
* @returns A promise that resolves once all tasks have been processed.
*/
declare function threadTasksAdvanced<TaskArguments>({ tasks, getMaxThreads, afterAll }: {
tasks: Task<TaskArguments>[];
getMaxThreads?: () => number;
afterAll?: () => any | (() => Promise<any>);
}): Promise<unknown>;
export { type Task, threadTasks, threadTasksAdvanced };