Code Monkey home page Code Monkey logo

thread's Introduction

alt text

nest badge alt text alt text alt text

  1. This module allows you to write Web Worker code inline with the rest of your code
  2. This module is also somewhat type safe
  3. Allows you to Thread already existing functions
  4. Allows module imports inside the worker

Examples

See examples folder for more examples

let thread = new Thread<number>((e: MessageEvent)=>{
    console.log('Worker: Message received from main script');
    const result = e.data[0] * e.data[1];
    if (isNaN(result)) {
      return 0;
    } else {
      console.log('Worker: Posting message back to main script');
      return(result);
    }
}, "module");

thread.onMessage((e)=>{
    console.log(`back from thread: ${e}`)
})
thread.postMessage([10, 12])

Instead of using the workers postMessage() method we return value from withing our method

Here's a few more examples

function someFunction(e: MessageEvent){
  return 0;
}

new Thread((e: MessageEvent)=>{return 0}, "module"); // inline Thread with return type of number
new Thread(someFunction, "module"); // thread an already existing function
new Thread(someFunction, "module", ['import Something from "../some.bundle.js";']); // thread with custom importing

Async support

const thread = new Thread<string, number>(async (_) => {
  console.log("Worker: Message received from main script");
  // Some async logic...
  await new Promise((ir) => setTimeout(ir, 2000));
  return "DONE";
}, "module");

thread.onMessage((e) => {
  console.log(`recived back from thread: ${e}`);
});

thread.postMessage(0);

API

Standard API

Method / variable Description
worker The Worker.
stopped Tells if the worker has been stopped
postMessage(msg) Sends data to the Thread
stop() calls terminate on the worker.
remove() Removes the current worker file from the temporary folder. NOTE: Can be used while the program is running (calls stop()..)
onMessage(callback: (e: T) =>void) Bind to the worker to receive messages

thread's People

Contributors

duart38 avatar grevend 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

Watchers

 avatar  avatar

thread's Issues

[RFC] Support async handler on thread function

I have proposal to make async handler works inside thread, Here is sample of async handler

import Thread from "../Thread.ts";

let thread = new Thread<number>(async (e: MessageEvent) => {
  console.log("Worker: Message received from main script");
  const result = e.data[0] * e.data[1];
  await new Promise((resolve) => setTimeout(resolve, 5 * 1000))
  if (isNaN(result)) {
    return 0;
  } else {
    console.log("Worker: Posting message back to main script");
    return (result);
  }
}, "module");

thread.onMessage((e) => {
  console.log(`recived back from thread: ${e}`);
});
thread.postMessage([10, 12]);
thread.postMessage([10, 10]);

//thread.stop();

It handy to have async handler so I can use await inside those function. I can prepare a PR if you want to implement this

Importing local bundle tries to import from path prefixed with denoland URL

I have simple folder structure:

  • deps.js - bundle which exports Abort
  • main.ts - file where I create worker and try to import Abort from deps.js
new Thread(fetcher, "module", ['import { Abort } from "./deps.js";'])
    .postMessage(config)
    .onMessage(handleResults);

Error I'm getting when running deno run --allow-read --allow-net main.ts

Download https://deno.land/x/[email protected]/deps.js
error: Uncaught (in promise) TypeError: Module not found "https://deno.land/x/[email protected]/deps.js".
      let x = await import(fqfn); //Deno.realPathSync(fqfn)
              ^
    at async Thread.copyDep (https://deno.land/x/[email protected]/Thread.ts:85:15)
    at async https://deno.land/x/[email protected]/Thread.ts:42:58
    at async Promise.all (index 0)
    at async Thread.populateFile (https://deno.land/x/[email protected]/Thread.ts:44:8)

I was trying to find why it's trying to import from https://deno.land/x/[email protected]/deps.js but no clue. It seams to be happening here but I don't know how to debug Deno import.

I basically just followed this example.

Is this possible or am I doing something wrong?

Unable to import local files in threads

consider this:

import Thread from "https://deno.land/x/[email protected]/Thread.ts";
import { Cat } from "./cat.ts";

const nWorkers = Math.max(Math.floor(navigator.hardwareConcurrency * 0.8), 2);


const threads: Array<Thread> = [];
for (let i = 0; i < nWorkers; ++i) {
  threads.push(
    new Thread<number | undefined, string>(
      (e) => {
        if (e.data.length === 0 || !e.data.length) return;
        const serializer = new Serializer({ classes: { Cat } });
        console.info(e.data);
        const cat: Cat = serializer.deserialize(e.data);
        cat.meow();
        return 0;
      },
      "module",
      [
        'import { Cat } from "./cat.ts"',
        'import { Serializer } from "https://deno.land/x/superserial/mod.ts"',
      ],
    ),
  );
}

let i = 0;
for (const thread of threads) {
  const cat = new Cat(`Matt${i}`);
  thread.onMessage((e) => {
    console.info(`thread -> ${i} : ${e}`);
    ++i;
    thread.stop();
  }).postMessage(serializer.serialize(cat));
}

It tries to import { Cat } from Download https://deno.land/x/[email protected]/cat.ts (1/2)???
I have no idea why it tries fetching it from there. Tried to debug it but i have no idea at which point it appends this library to it...

Paths not correct when importing from net

error: Uncaught Error: Import 'https://raw.githubusercontent.com/duart38/Thread/master/tmp_threads/deno_thread_4bcab5c4.js' failed: 404 Not Found
    at Worker.#poll (rt/11_workers.js:178:19)

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.