Simple Threading with JS through NodeJS Cluster
const thread = ; { console;} const thr = ;thr;thr;thr;
Table of Contents
Features
- Supports "require" in "threaded" functions
- Supports storing both synchronous and asynchronous functions
- Multiple threads running simultaneously
- Thread emitted events
- Thread cleanup
Installing
Requires prior installation of NodeJS
$ npm install thread-process
Initializing
const thread = ;
Properties
ThreadMAX_THREADS // Gets the maximum CPU countThreadOPEN_THREADS // Gets the count of how many threads are active
Thread Class
Constructor
; // Constructing a thread with default settings; // Stores a function
Storing Functions (Asynchronous)
(Async) returns the function stored
thr
Global Variables Accessible
THREAD_DATA // (Object) Contains all the functions storedFOCUSED_FUNCTION // (String) The most recent functionRETURN(data); // Sends data from the function to the main thread
Running Functions (Asynchronous)
Run the most recent function stored or executed by the thread
(Async) returns the data returned by the function executed
thr;thr; // Closes the thread after running
Run target function stored in the thread
thr; // Runs temp()
Run with arguments
thr
Running Multiple Threads (Asynchronous)
(Async) returns data as an Array
Thread;
Events
Event handling can make life much easier!
thr; // Contains the returned datathr; // Contains data returned by RETURN(data);
Closing Threads
thr;
Immediate Thread (Asynchronous)
Runs a function within a thread and immediately closes the thread upon completion
(Async) returns the data returned by the function executed
Thread
Example Usage
Using thread constiables
const temp = { console; console; // Outputs "temp"}{ const tp = ; await tp; await tp;};
Asynchronous management of threads & passing values
const temp = async { console;}{ const tp = ; await tp; await tp;};
Multiple stored functions
const func1 = {console}const func2 = {console}{ const tp = ; await tp; await tp; await tp;};
Using then instead of async/await
const temp = {console}const tp = ;tp;
Running simultaneous threads
const temp = {return "Hello";}const tp = temp;const tp2 = temp;Thread;
Running with events
const temp = {};const tp = temp;tp;tp;