Before you go, check out these stories!

0
Hackernoon logoVery simple implementation multi thread in Node.js by@luklukluhuringsantoso

Very simple implementation multi thread in Node.js

Author profile picture

@luklukluhuringsantosoLukluk Luhuring Santoso

Let’s start killing a Processor with single thread

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

$time node app.js
28.04 secs

//async process
function slowSquareAsync(){
setTimeout(function(args) {
let i = 0;
let n = 100000
while (++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

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

Tags

The Noonification banner

Subscribe to get your daily round-up of top tech stories!