All Projects → andywer → Threads.js

andywer / Threads.js

Licence: mit
🧵 Make web workers & worker threads as simple as a function call.

Programming Languages

javascript
184084 projects - #8 most used programming language
typescript
32286 projects

Projects that are alternatives of or similar to Threads.js

Hamsters.js
100% Vanilla Javascript Multithreading & Parallel Execution Library
Stars: ✭ 517 (-61.07%)
Mutual labels:  multithreading, web-worker, thread-pool
super-workers
🐴 Distribute load on front-end via parallelism
Stars: ✭ 93 (-93%)
Mutual labels:  web-worker, thread-pool
mvThreadPool
An easy to use C++ Thread Pool
Stars: ✭ 30 (-97.74%)
Mutual labels:  multithreading, thread-pool
Java Concurrency Examples
Java Concurrency/Multithreading Tutorial with Examples for Dummies
Stars: ✭ 173 (-86.97%)
Mutual labels:  multithreading, thread-pool
ParallelQSlim
Shape Aware Parallel Mesh Simplification Algorithm
Stars: ✭ 84 (-93.67%)
Mutual labels:  multithreading, thread-pool
thread-pool
BS::thread_pool: a fast, lightweight, and easy-to-use C++17 thread pool library
Stars: ✭ 1,043 (-21.46%)
Mutual labels:  multithreading, thread-pool
TaskManager
A C++14 Task Manager / Scheduler
Stars: ✭ 81 (-93.9%)
Mutual labels:  multithreading, thread-pool
Esdatatool
一个多线程备份恢复es索引的微服务
Stars: ✭ 68 (-94.88%)
Mutual labels:  multithreading
Zippyshare Scraper
A module to get direct downloadable links from zippyshare download page.
Stars: ✭ 77 (-94.2%)
Mutual labels:  multithreading
Tdp
The Darkest Pipeline - Multithreaded pipelines for modern C++
Stars: ✭ 67 (-94.95%)
Mutual labels:  multithreading
Pelagia
Automatic parallelization (lock-free multithreading thread) tool developed by Surparallel Open Source.Pelagia is embedded key value database that implements a small, fast, high-reliability on ANSI C.
Stars: ✭ 1,132 (-14.76%)
Mutual labels:  multithreading
Evenk
A C++ library for concurrent programming
Stars: ✭ 68 (-94.88%)
Mutual labels:  multithreading
Unity Experiment Framework
UXF - Framework for creating human behaviour experiments in Unity
Stars: ✭ 81 (-93.9%)
Mutual labels:  multithreading
Pastebin Scraper
Live-scraping pastebin to fight boredom.
Stars: ✭ 66 (-95.03%)
Mutual labels:  multithreading
Blog
Java Performance
Stars: ✭ 83 (-93.75%)
Mutual labels:  thread-pool
Archive Password Cracker
设计精良的压缩包密码破解工具,具有自定义字典、导出字典、选择字典等功能。基于Python实现,支持多线程与多进程,不断完善中……
Stars: ✭ 65 (-95.11%)
Mutual labels:  multithreading
So 5 5
SObjectizer: it's all about in-process message dispatching!
Stars: ✭ 87 (-93.45%)
Mutual labels:  multithreading
Ngx Papaparse
Papa Parse wrapper for Angular
Stars: ✭ 83 (-93.75%)
Mutual labels:  multithreading
Operating Systems
'Operating System Concepts' - Solutions to exercises and projects
Stars: ✭ 76 (-94.28%)
Mutual labels:  multithreading
Memento
Fairly basic redis-like hashmap implementation on top of a epoll TCP server.
Stars: ✭ 74 (-94.43%)
Mutual labels:  thread-pool

threads.js

Build status npm (tag) Chat room


Offload CPU-intensive tasks to worker threads in node.js, web browsers and electron using one uniform API.

Uses web workers in the browser, worker_threads in node 12+ and tiny-worker in node 8 to 11.

Features

  • First-class support for async functions & observables
  • Write code once, run it on all platforms
  • Manage bulk task executions with thread pools
  • Use require() and import/export in workers
  • Works great with webpack

Version 0.x

You can find the old version 0.12 of threads.js on the v0 branch. All the content on this page refers to version 1.0 which is a rewrite of the library with a whole new API.

Installation

npm install threads tiny-worker

You only need to install the tiny-worker package to support node.js < 12. It's an optional dependency and used as a fallback if worker_threads are not available.

Platform support

Run on node.js

Running code using threads.js in node works out of the box.

Note that we wrap the native Worker, so new Worker("./foo/bar") will resolve the path relative to the module that calls it, not relative to the current working directory.

That aligns it with the behavior when bundling the code with webpack or parcel.

Webpack build setup

Webpack config

Use with the threads-plugin. It will transparently detect all new Worker("./unbundled-path") expressions, bundles the worker code and replaces the new Worker(...) path with the worker bundle path, so you don't need to explicitly use the worker-loader or define extra entry points.

  npm install -D threads-plugin

Then add it to your webpack.config.js:

+ const ThreadsPlugin = require('threads-plugin');

  module.exports = {
    // ...
    plugins: [
+     new ThreadsPlugin()
    ]
    // ...
  }

Node.js bundles

If you are using webpack to create a bundle that will be run in node (webpack config target: "node"), you also need to specify that the tiny-worker package used for node < 12 should not be bundled:

  module.exports = {
    // ...
+   externals: {
+     "tiny-worker": "tiny-worker"
+   }
    // ...
}

Make sure that tiny-worker is listed in your package.json dependencies in that case.

When using TypeScript

Make sure the TypeScript compiler keeps the import / export statements intact, so webpack resolves them. Otherwise the threads-plugin won't be able to do its job.

  module.exports = {
    // ...
    module: {
      rules: [
        {
          test: /\.ts$/,
          loader: "ts-loader",
+         options: {
+           compilerOptions: {
+             module: "esnext"
+           }
+         }
        }
      ]
    },
    // ...
  }
Parcel bundler setup

You need to import threads/register once at the beginning of your application code (in the master code, not in the workers):

  import { spawn } from "threads"
+ import "threads/register"

  // ...

  const work = await spawn(new Worker("./worker"))

This registers the library's Worker implementation for your platform as the global Worker. This is necessary, since you cannot import { Worker } from "threads" or Parcel won't recognize new Worker() as a web worker anymore.

Be aware that this might affect any code that tries to instantiate a normal web worker Worker and now instead instantiates a threads.js Worker. The threads.js Worker is just a web worker with some sugar on top, but that sugar might have unexpected side effects on third-party libraries.

Everything else should work out of the box.

Getting Started

Basics

// master.js
import { spawn, Thread, Worker } from "threads"

const auth = await spawn(new Worker("./workers/auth"))
const hashed = await auth.hashPassword("Super secret password", "1234")

console.log("Hashed password:", hashed)

await Thread.terminate(auth)
// workers/auth.js
import sha256 from "js-sha256"
import { expose } from "threads/worker"

expose({
  hashPassword(password, salt) {
    return sha256(password + salt)
  }
})

spawn()

The hashPassword() function of the auth object in the master code proxies the call to the hashPassword() function in the worker:

If the worker's function returns a promise or an observable then you can just use the return value as such in the master code. If the function returns a primitive value, expect the master function to return a promise resolving to that value.

expose()

Use expose() to make a function or an object containing methods callable from the master thread.

In case of exposing an object, spawn() will asynchronously return an object exposing all the object's functions. If you expose() a function, spawn will also return a callable function, not an object.

Usage

Find the full documentation on the website:

Webpack

Threads.js works with webpack. Usually all you need to do is adding the threads-plugin.

See Build with webpack on the website for details.

Debug

We are using the debug package to provide opt-in debug logging. All the package's debug messages have a scope starting with threads:, with different sub-scopes:

  • threads:master:messages
  • threads:master:spawn
  • threads:master:thread-utils
  • threads:pool:${poolName || poolID}

Set it to DEBUG=threads:* to enable all the library's debug logging. To run its tests with full debug logging, for instance:

DEBUG=threads:* npm test

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].