paint-brush
Very simple implementation multi thread in Node.jsby@luklukluhuringsantoso
3,587 reads
3,587 reads

Very simple implementation multi thread in Node.js

by Lukluk Luhuring SantosoNovember 3rd, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Let’s start killing a <a href="https://hackernoon.com/tagged/processor" target="_blank">Processor</a> with single thread
featured image - Very simple implementation multi thread in Node.js
Lukluk Luhuring Santoso HackerNoon profile picture

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.