• Stars
    star
    229
  • Rank 174,666 (Top 4 %)
  • Language
    TypeScript
  • License
    Other
  • Created over 4 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Recursive Worker Threads in NodeJS

ThreadBox

Recursive Worker Threads in NodeJS

npm version Build Status

Example

The following replicates the above worker graph.

import { Thread, Sender, Receiver } from '@sinclair/threadbox'

const WorkerC = Thread.Worker(class {
  run() {
    return Math.random()
  }
})

const WorkerB = Thread.Worker(class {
  async run(sender: Sender) {
    const c_0 = Thread.Spawn(WorkerC)
    const c_1 = Thread.Spawn(WorkerC)
    const c_2 = Thread.Spawn(WorkerC)
    const c_3 = Thread.Spawn(WorkerC)
    const [a, b, c, d] = await Promise.all([
      c_0.run(),
      c_1.run(),
      c_2.run(),
      c_3.run(),
    ])
    await sender.send([a, b, c, d])
    await sender.end()
    await c_0.dispose()
    await c_1.dispose()
    await c_2.dispose()
    await c_3.dispose()
  }
})
const WorkerA = Thread.Worker(class {
  async run(receiver: Receiver) {
    for await(const [a, b, c, d] of receiver) { }
  }
})

// start here ...
Thread.Main(() => {
  const [sender, receiver] = Thread.Channel()
  const a = Thread.Spawn(WorkerA)
  const b = Thread.Spawn(WorkerB)
  await Promise.all([
    a.run(receiver),
    b.run(sender) 
  ])
  await a.dispose()
  await b.dispose()
})

Overview

ThreadBox is a threading library for JavaScript built on top of NodeJS worker_threads. It is written to allow for compute intensive and potentially blocking JavaScript routines to be easily executed in remote worker threads. ThreadBox uses a recursive threading model, where spawned threads are created by re-running the applications entry module (typically app.js). This approach allows for ergonomic threading, but requires code executed in the global scope to be moved into functions and classes.

This project is written as a research project to explore the potential for recursive threading in Node. It is offered to anyone who may find it of use.

Licence MIT

Install

$ npm install @sinclair/threadbox --save

Contents

Main

Use Thread.Main(...) to define the application entry point. This function will only be called once when the process starts, and ignored for subsequent threads.

import { Thread } from '@sinclair/threadbox'

Thread.Main(() => {
  
  console.log('Hello World')
  
})

Worker

Use Thread.Worker(...) to denote a class as threadable. This enables the class to be spawned via Thread.Spawn(...). The return type of this function returns the inner constructor that can be instanced in the current thread.

import { Thread } from '@sinclair/threadbox'

const Basic = Thread.Worker(class {
    add(a: number, b: number) {
        return a + b
    }
    dispose() { 
        console.log('disposed!')
    }
})

Thread.Main(async () => {
    // instance as thread
    const thread = Thread.Spawn(Basic)
    console.log(await thread.add(10, 20))
    await thread.dispose()

    // instance as local
    const local = new Basic()
    console.log(local.add(10, 20))
})

Spawn

The Thread.Spawn(...) to spawn a new constructor in a remote worker thread. This function takes the threadable constructor as it's first argument followed by any parameters defined for the constructor.

import { Thread } from '@sinclair/threadbox'

const Runner = Thread.Worker(class {
  constructor(private taskName: string) {
    console.log(`Runner: ${taskName}`)
  }
  process() {
    console.log(`Runner: execute: ${taskName}`)
  }
  dispose() {
    console.log(`Runner: dispose ${taskName}`)
  }
})

Thread.Main(async () => {
  const runner = Thread.Spawn(Runner, 'Name of Runner')
  await runner.process()
  await runner.dispose()
})

Channel

Use Thread.Channel<T>() to create a messaging channel to communicate between threads.

import { Thread, Sender, Receiver } from '@sinclair/threadbox'

const Numbers = Thread.Worker(class {
  start(sender: Sender<number>) {
    for(let i = 0; i < 1024; i++) {
        sender.send(i)
    }
  }
})

Thread.Main(async () => {
  const thread = Thread.Spawn(Numbers)
  const [sender, receiver] = Thread.Channel<number>()
  thread.start(sender)
  
  // await values on receiver
  for await(const value of receiver) {
    console.log(value)
  }

  await thread.dispose()
})

Marshal

Use Thread.Marshal(...) to denote a constructor should be marshalled across threads. This enables class instances to be transferred to remote threads for remote invocation.

import { Thread } from '@sinclair/threadbox'

const Transferrable = Thread.Marshal({
    method() {
        console.log('Hello World')
    }
})

const Worker = Thread.Worker({
    execute(transferable: Transferrable) {
        transferable.method() // callable
    }
}

Thread.Main(() => {
  const thread = spawn(Worker)
  const transferable = new Transferrable()
  await thread.execute(transferable)
  await thread.dispose()
})

Note: There is a serialization cost to marshaling. For performance, only Marshal when you need to dynamically move logic in and out of threads.

Mutex

Use Thread.Mutex(...) to create a lock on critical sections. This should only be used when two threads reference the same SharedArrayBuffer.

import { Thread, Mutex } from '@sinclair/threadbox'

const Worker = Thread.Worker(class {
  constructor(private readaonly mutex: Mutex) {}

  execute(data: Uint8Array, value: number) {
    this.mutex.lock()
    data[0] = value
    data[1] = value
    data[2] = value
    data[3] = value
    this.mutex.unlock()
  }
})

Thread.Main(async () => {

  const mutex = Thread.Mutex()

  const threads = [
    Thread.Spawn(Worker, mutex),
    Thread.Spawn(Worker, mutex),
    Thread.Spawn(Worker, mutex),
    Thread.Spawn(Worker, mutex)
  ]

  const shared = new Uint8Array(new SharedArrayBuffer(4 * Float32Array.BYTES_PER_ELEMENT))

  await Promise.all([
    threads[0].execute(shared)
    threads[1].execute(shared)
    threads[2].execute(shared)
    threads[3].execute(shared)
  ])

  await Promise.all([
    threads[0].dispose()
    threads[1].dispose()
    threads[2].dispose()
    threads[3].dispose()
  ])
})

More Repositories

1

typebox

Json Schema Type Builder with Static Type Resolution for TypeScript
TypeScript
4,648
star
2

zero

A 3D renderer written in JavaScript and rendered to the terminal.
TypeScript
2,413
star
3

smoke

Run Web Servers in Web Browsers over WebRTC
TypeScript
520
star
4

hammer

Build Tool for Browser and Node Applications
TypeScript
234
star
5

linqbox

Language Integrated Query for JavaScript
TypeScript
130
star
6

typescript-bundle

A Bundling Tool for TypeScript
TypeScript
125
star
7

typebox-codegen

Code Generation for TypeBox Types
TypeScript
120
star
8

sidewinder

Type Safe Micro Services for Node
TypeScript
59
star
9

blender-node

NodeJS binding to Blenders Python Scripting Environment
TypeScript
59
star
10

typebox-workbench

Type Transform Tool for Runtime Type Systems
TypeScript
46
star
11

reactor

Asynchronous Event Driven IO for .NET
C#
44
star
12

ts-8-bit

Using TypeScript's Type System to do 8-bit Arithmetic
TypeScript
37
star
13

tesseract

WebGL 2.0 GPGPU compute library for JavaScript.
TypeScript
32
star
14

fastify-typebox

Enhanced TypeBox support for Fastify
TypeScript
31
star
15

typescript.api

A typescript 0.9 compiler as a service api for nodejs.
TypeScript
27
star
16

black

A Software Rasterizer written in Rust
Rust
25
star
17

servicebox

Typed Web Services for NodeJS
TypeScript
22
star
18

esbuild-wasm-resolve

File Resolution for Esbuild running in the Browser
TypeScript
20
star
19

appex

develop nodejs web applications with typescript
TypeScript
16
star
20

carbon

Compatibility Layer for Node Deno and Bun
TypeScript
16
star
21

drift

Run Chrome from the Terminal
TypeScript
15
star
22

fs-effects

A library for composing various file, folder, shell and watch operations in node.
TypeScript
10
star
23

smoke-task

Runs JavaScript functions from a terminal
TypeScript
9
star
24

neuron

Neural network implemented in JavaScript
TypeScript
9
star
25

corsa

Asynchronous uni-directional channels in node using async iteration.
TypeScript
9
star
26

smoke-rs

lightweight async task and stream library for Rust
Rust
8
star
27

stream-cortex

real-time live video streaming experiments with node + ffmpeg
TypeScript
8
star
28

magnum

general purpose template engine for nodejs.
TypeScript
7
star
29

runtime-type-benchmarks

High Performance Validation Benchmarks for JavaScript
TypeScript
6
star
30

vector-cs

.NET opengl graphics library
C#
6
star
31

tasksmith

Task automation library for node.
TypeScript
5
star
32

phantom-network-service

run phantomjs as a network service
TypeScript
5
star
33

neuron-render

An experiment using neural networks to approximate various stages of graphics pipeline for the purpose of creating interesting things.
TypeScript
5
star
34

neuron-gpgpu

GPGPU based implementation of a multi layer perceptron network for the browser.
TypeScript
5
star
35

fpv32

Benchmarks for fast 32-bit floating point vector math for JavaScript.
TypeScript
5
star
36

statebox

An observable JavaScript state container
TypeScript
4
star
37

hexagon

WebGL 2.0 graphics renderer written in TypeScript
TypeScript
4
star
38

smoke-run

Runs shell commands on file system watch events.
TypeScript
4
star
39

crimson-rust

CSP experiments in the rust programming language
Rust
4
star
40

fsweb

Static HTTP development server with live reload on save.
TypeScript
4
star
41

pubsub-rs

simple tcp based pubsub for rust
Rust
3
star
42

crimson

Actor system in JavaScript
TypeScript
3
star
43

merc

blender scene renderer demo
TypeScript
3
star
44

bayes

An implementation of a naive bayes classifier in TypeScript
JavaScript
3
star
45

three-instanced-mesh

A reference project enabling geometry instancing for threejs materials
TypeScript
3
star
46

signature

Overloaded function signatures in JavaScript.
TypeScript
2
star
47

smoke-web

A static file server that live reloads on file change.
TypeScript
2
star
48

smoke-hub-appengine

messaging hub for webrtc targeting the google app engine standard environment.
Go
2
star
49

fsrun

Restart OS processes on file system watch events.
JavaScript
2
star
50

smoke-pack

A npm project provisioning and build system for browser, electron, node and library projects.
TypeScript
1
star
51

vlc.web.stream

Example and documentation about streaming from VLC to a browser.
JavaScript
1
star
52

taxman

simple book keeping application for nodejs
JavaScript
1
star
53

neuron-function-approximation

An experiment using neural networks to approximate pure functions
TypeScript
1
star
54

nx-transform

angular + threejs + css experiment
HTML
1
star
55

deno-minifb

Render 32-bit RGBA Buffers to Desktop Windows
Rust
1
star
56

vector-rs

vector math library and utilities for Rust.
Rust
1
star
57

brainfuck-rs

A brainfuck interpreter implemented in Rust.
Rust
1
star
58

pang

A simple dependency injection library for node
TypeScript
1
star