Very simple implementation multi thread in Node.js

Written by luklukluhuringsantoso | Published 2017/11/03
Tech Story Tags: javascript | multithread | threads | nodejs

TLDRvia the TL;DR App

Let’s start killing a Processor with single thread

//sync processfunction slowSquare(n){var i = 0;while (++i < n * n) {}}

slowSquare(100000)slowSquare(100000)

$time node app.js **28.04 secs**

//async processfunction slowSquareAsync(){setTimeout(function(args) {let i = 0;let n = 100000while (++i < n * n) {}}, 1)}

slowSquareAsync()slowSquareAsync()

$time node app.js Waiting too long then I aborted (ctrl+c) after wait about 4mins

And why my laptop coming hot? :D

After read few article I found this

Then I tried create very small module, I called Iyem.js , iyem meaning is maid in Bahasa

I will try same code but using Iyem.js

let iyem = require('iyem')

let slowSquareThread = iyem.create(function(){var i = 0;var n = 100000;while (++i < n * n) {}$.finish(i);})slowSquareThread.start()slowSquareThread.onFinish(function(result,err){console.log(result,err)})

function slowSquare(n){var i = 0;while (++i < n * n) {}}

slowSquare(100000)

$time node app.js **13.2 secs**

Wow, cool right? , let’s try more complex multi thread with communication between thread (Pub Sub)

let iyem = require('iyem')

let importDataReportWorker = iyem.create(function(){const parse = require('parse-csv')const fs = require('fs')const reconcile = require('./Reconcile')parse(fs.readFileSync("./200MB.csv", "utf-8"),function(err,report){$.sub("GET_TRX_SETTELMENT_COLLECTION_DONE",function(dataTrx){var result = reconcile(report,dataTrx)$.finish(result)})})})

let getTrxCollection = iyem.create(function(){const db = require('./db')db.find({transaction_date:"2017-10-10"},function(err,collection){if(err) $.error(err)$.pub("GET_TRX_SETTELMENT_COLLECTION_DONE",collection)$.finish()})})

getTrxCollection.start()importDataReportWorker.start().onFinish(function(err,result){console.log("DONE")console.log(result)})

this is just experimental, Please give me your feedback and dont forget to clap or share

iyem_Easy way to manage Multi Thread Js_www.npmjs.com

lukluk/iyem_iyem - Nodejs with Multi Thread_github.com

If you learned something, click the 💚 to help others find this article.


Published by HackerNoon on 2017/11/03