alepha@docs:~/docs/packages/alepha$
cat thread.md
2 min read
Last commit:

#Alepha - Thread

#Installation

Part of the alepha package. Import from alepha/thread.

npm install alepha

#Overview

Simple interface for managing worker threads in Alepha.

#API Reference

#Primitives

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.

#$thread()

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

  • Thread Pool Management: Automatically manages a pool of worker threads with configurable limits
  • Thread Reuse: Reuses existing threads to avoid expensive initialization overhead
  • Idle Cleanup: Automatically terminates unused threads after a configurable timeout
  • Type-Safe Communication: Optional TypeBox schema validation for data passed to threads
  • CPU-Aware Defaults: Pool size defaults to CPU count × 2 for optimal performance
  • Error Handling: Proper error propagation and thread cleanup on failures

Use Cases

Perfect for CPU-intensive tasks that would otherwise block the main thread:

  • Image/video processing
  • Data transformation and analysis
  • Cryptographic operations
  • Heavy computations and algorithms
  • Background data processing

Basic thread usage:

ts
 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:

ts
 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:

ts
 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:

ts
 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}
On This Page
No headings found...
ready
mainTypeScript
UTF-8packages_alepha_thread.md