Skip to content

Node-Threads-Pool: A Node.js library for efficient task execution in child threads, with a thread pool for CPU-intensive tasks and multi-core processing.

License

Notifications You must be signed in to change notification settings

pxgo/node-threads-pool

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

node-threads-pool

David deps node version npm download npm license

Installation

npm install node-threads-pool

Usage

const tp = new Eve(filename, threadCount);
  • @param {String} filename: The path to the Worker’s main script or module. Detail description
  • @param {Number} threadCount: The number of threads in the thread pool
tp.run(workerData);
  • @param {Object} workerData: Any JavaScript value that will be cloned and made available as require('worker_threads').workerData. Detail description
  • @return {Promise} The result
const thread = new Thread(func);
  • @param {Function} func: some code

Example

1. Open 20 threads to perform some calculations

// main.js

const {Eve} = require('node-threads-pool');

const tp = new Eve('thread.js', 20);
module.exports = async (data) => {
  return await tp.run(data);
};

// thread.js

const {Thread} = require('node-threads-pool');

const thread = new Thread(async (data) => {
  return await doSomething(data);
});

Or write to the same JS file

// main.js

const {Eve, Thread, isMainThread} = require('node-threads-pool');

async function threadFunc() {
  const thread = new Thread(async (data) => {
    return await doSomething(data);
  });
}

if(isMainThread) {
  const tp = new Eve(__filename, 20);
  module.exports = async function(data) {
    return await tp.run(data);
  };
} else {
  threadFunc();
}

2. Render PUG to HTML

const pug = require('pug');
const os = require('os');
const {Eve, Thread, isMainThread} = require('node-threads-pool');

async function threadFunc() {
  const options = {};
  const thread = new Thread(_data => {
    const {template, data} = _data;
    options.data = data;
    return pug.renderFile(template, options);
  });
}

if(!isMainThread) {
  threadFunc();
} else {
  const tp = new Eve(__filename, os.cpus().length);
  module.exports = async (template, data) => {
    return await tp.run({
      template, data
    });
  };
}

Test

npm run eve

About

Node-Threads-Pool: A Node.js library for efficient task execution in child threads, with a thread pool for CPU-intensive tasks and multi-core processing.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published