Part of the alepha package. Import from alepha/thread.
npm install alepha
Simple interface for managing worker threads in Alepha.
Primitives are functions that define and configure various aspects of your application. They follow the convention of starting with $ and return configured primitive instances.
For more details, see the Primitives documentation.
Creates a worker thread primitive for offloading CPU-intensive tasks to separate threads.
This primitive enables you to run JavaScript code in Node.js worker threads, allowing you to leverage multiple CPU cores and avoid blocking the main event loop. It provides a pool-based approach with intelligent thread reuse and automatic lifecycle management.
Key Features
Use Cases
Perfect for CPU-intensive tasks that would otherwise block the main thread:
Basic thread usage:
1import { $thread } from "alepha/thread"; 2 3class DataProcessor { 4 heavyComputation = $thread({ 5 name: "compute", 6 handler: async () => { 7 // This runs in a separate worker thread 8 let result = 0; 9 for (let i = 0; i < 1000000; i++) {10 result += Math.sqrt(i);11 }12 return { result, timestamp: Date.now() };13 }14 });15 16 async processData() {17 // Execute in worker thread without blocking main thread18 const result = await this.heavyComputation.execute();19 console.log(`Computation result: ${result.result}`);20 }21}
Configured thread pool with custom settings:
1class ImageProcessor { 2 imageProcessor = $thread({ 3 name: "image-processing", 4 maxPoolSize: 4, // Limit to 4 concurrent threads 5 idleTimeout: 30000, // Clean up idle threads after 30 seconds 6 handler: async () => { 7 // CPU-intensive image processing logic 8 return await processImageData(); 9 }10 });11}
Thread with data validation:
1import { t } from "alepha"; 2 3class CryptoService { 4 encrypt = $thread({ 5 name: "encryption", 6 handler: async () => { 7 // Perform encryption operations 8 return await encryptData(); 9 }10 });11 12 async encryptSensitiveData(data: { text: string; key: string }) {13 // Validate input data before sending to thread14 const schema = t.object({15 text: t.text(),16 key: t.text()17 });18 19 return await this.encrypt.execute(data, schema);20 }21}
Parallel processing with multiple threads:
1class BatchProcessor { 2 processor = $thread({ 3 name: "batch-worker", 4 maxPoolSize: 8, // Allow up to 8 concurrent workers 5 handler: async () => { 6 return await processBatchItem(); 7 } 8 }); 9 10 async processBatch(items: any[]) {11 // Process multiple items in parallel across different threads12 const promises = items.map(() => this.processor.execute());13 const results = await Promise.all(promises);14 return results;15 }16}