Multithreading is a TypeScript library that brings robust, Rust-inspired concurrency primitives to the JavaScript ecosystem. It provides a thread-pool architecture, strict memory safety semantics, and synchronization primitives like Mutexes, Read-Write Locks, and Condition Variables.
This library is designed to abstract away the complexity of managing WebWorkers , serialization, and SharedArrayBuffer complexities, allowing developers to write multi-threaded code that looks and feels like standard asynchronous JavaScript.
Installation
npm install multithreading
Core Concepts
JavaScript is traditionally single-threaded. To achieve true parallelism, this library uses Web Workers. However, unlike standard Workers, this library offers:
Managed Worker Pool: Automatically manages a pool of threads based on hardware concurrency. Shared Memory Primitives: Tools to safely share state between threads without race conditions. Scoped Imports: Support for importing external modules and relative files directly within worker tasks. Move Semantics: Explicit data ownership transfer to prevent cloning overhead.
Quick Start
The entry point for most operations is the spawn function. This submits a task to the thread pool and returns a handle to await the result.
import { spawn } from "multithreading" ; // Spawn a task on a background thread const handle = spawn ( ( ) => { // This code runs in a separate worker const result = Math . random ( ) ; return result ; } ) ; // Wait for the result const result = await handle . join ( ) ; if ( result . ok ) { console . log ( "Result:" , result . value ) ; // 0.6378467071314606 } else { console . error ( "Worker error:" , result . error ) ; }
... continue reading