Coder Social home page Coder Social logo

w4g1 / multithreading Goto Github PK

View Code? Open in Web Editor NEW
295.0 5.0 10.0 439 KB

⚡ Multithreading functions in JavaScript to speedup heavy workloads, designed to feel like writing vanilla functions.

Home Page: https://multithreading.io

License: MIT License

TypeScript 66.81% JavaScript 33.19%
es6-generators multithreading threads webworkers worker-threads concurrency javascript multi-threading nodejs parallel-processing

multithreading's Introduction

Multithreading Banner

License Downloads NPM version GitHub Repo stars Node.js CI

multithreading

Multithreading is a tiny runtime that allows you to execute JavaScript functions on separate threads. It is designed to be as simple and fast as possible, and to be used in a similar way to regular functions.

With a minified size of only 4.5kb, it has first class support for Node.js, Deno and the browser. It can also be used with any framework or library such as React, Vue or Svelte.

Depending on the environment, it uses Worker Threads or Web Workers. In addition to ES6 generators to make multithreading as simple as possible.

The State of Multithreading in JavaScript

JavaScript's single-threaded nature means that tasks are executed one after the other, leading to potential performance bottlenecks and underutilized CPU resources. While Web Workers and Worker Threads offer a way to offload tasks to separate threads, managing the state and communication between these threads is often complex and error-prone.

This project aims to solve these challenges by providing an intuitive Web Worker abstraction that mirrors the behavior of regular JavaScript functions. This way it feels like you're executing a regular function, but in reality, it's running in parallel on a separate threads.

Installation

npm install multithreading

Usage

Basic example

import { threaded } from "multithreading";

const add = threaded(function* (a, b) {
  return a + b;
});

console.log(await add(5, 10)); // 15

The add function is executed on a separate thread, and the result is returned to the main thread when the function is done executing. Consecutive invocations will be automatically executed in parallel on separate threads.

Example with shared state

import { threaded, $claim, $unclaim } from "multithreading";

const user = {
  name: "john",
  balance: 0,
};

const add = threaded(async function* (amount) {
  yield user; // Add user to dependencies

  await $claim(user); // Wait for write lock

  user.balance += amount;

  $unclaim(user); // Release write lock
});

await Promise.all([
  add(5),
  add(10),
]);

console.log(user.balance); // 15

This example shows how to use a shared state across multiple threads. It introduces the concepts of claiming and unclaiming write access using $claim and $unclaim. This is to ensure that only one thread can write to a shared state at a time.

Always $unclaim() a shared state after use, otherwise the write lock will never be released and other threads that want to write to this state will be blocked indefinitely.

The yield statement is used to specify external dependencies, and must be defined at the top of the function.

Example with external functions

import { threaded, $claim, $unclaim } from "multithreading";

// Some external function
function add (a, b) {
  return a + b;
}

const user = {
  name: "john",
  balance: 0,
};

const addBalance = threaded(async function* (amount) {
  yield user;
  yield add; // Add external function to dependencies

  await $claim(user);

  user.balance = add(user.balance, amount);

  $unclaim(user);
});


await Promise.all([
  addBalance(5),
  addBalance(10),
]);

console.log(user.balance); // 15

In this example, the add function is used within the multithreaded addBalance function. The yield statement is used to declare external dependencies. You can think of it as a way to import external data, functions or even packages.

As with previous examples, the shared state is managed using $claim and $unclaim to guarantee proper synchronization and prevent data conflicts.

External functions like add cannot have external dependencies themselves. All variables and functions used by an external function must be declared within the function itself.

Using imports from external packages

When using external modules, you can dynamically import them by using yield "some-package". This is useful when you want to use other packages within a threaded function.

import { threaded } from "multithreading";

const getId = threaded(function* () {
  /**
   * @type {import("uuid")}
   */
  const { v4 } = yield "uuid"; // Import other package

  return v4();
}

console.log(await getId()); // 1a107623-3052-4f61-aca9-9d9388fb2d81

You can also import external modules in a variety of other ways:

const { v4 } = yield "npm:uuid"; // Using npm specifier (available in Deno)
const { v4 } = yield "https://esm.sh/uuid"; // From CDN url (available in browser and Deno)

Enhanced Error Handling

Errors inside threads are automatically injected with a pretty stack trace. This makes it easier to identify which line of your function caused the error, and in which thread the error occured.

Example of an enhanced stack trace

multithreading's People

Contributors

w4g1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

multithreading's Issues

use this library for 3rd party scripts

hey - found this after 20 in search, and is not an issue, is more a question... could this library be used to load 3rd party scripts as google tag manager or analytics? I know that SW cannot access to the page, but I'm not an expert on this item.

I'm thinking something like...

html

<body>

      <!-- Example of custom type script -->
      <script type="type/multithreading">
        console.log('Script 1 is running.');
        // Additional JavaScript code for Script 1...
    </script>

    <script type="type/multithreading">
        console.log('Script 2 is running.');
        // Additional JavaScript code for Script 2...
    </script>

    <!-- Standard script to execute custom type scripts -->
   
    <div id="app"></div>
    <script type="module" src="/main.js"></script>

  </body>

js

import { threaded } from "multithreading";

const add = threaded(function* (a, b){
    document.querySelectorAll('script[type="type/multithreading"]').forEach(script => {
      try {
          new Function(script.innerText)();
      } catch (e) {
          console.error('Error executing multithreading script:', e);
      }
  });
});
await add()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.