Simple way producer–consumer problem's implementation in NodeJs


Problem Name : 
Producer-Consumer Problem (Also Known as Bounded Buffer Problem)

Goal : 
It's explain you "multi-process resource synchronization problem".

Problem Statement : 
there are many producers and many consumers, the work of producer is to generate/produce things/jobs/items any things and the work of consumer is to consume things/jobs/items/any things produced/generated by producer.

What is the NodeJs ?
                 Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

Code :
var express = require('express');
var app = express();
var queue = [];

//Default Handler
app.get('/',function(req,res){
res.send('Producer/Consumer Server');
});


//Producer Handler
app.get('/producer',function(req,res){
res.send('Nothing for Producer Usage /producer/{number}');
})
//Producer Handler with Input Id
app.get('/producer/:id',function(req,res){
var producerId = req.params["id"];

if(producerId == "" ||producerId.length != 0 ){
    res.send('Producer Put : '+producerId);
    queue.push(producerId);
}else{
    res.send('Nothing for Producer');
}
});

//Consumer Handler
app.get('/consumer',function(req,res){
    if(queue.length != 0){
        res.send('Consumer Get : '+queue.pop());
    }else{
        res.send('Nothing for Consumer');
    }
})

app.listen(8084);


Comments

Unknown said…
I believe you want to use shift, not pop, if you intended this to act like a FIFO queue.
javaamtho said…
@tony, yes ..current one is LIFO queue and can make it FIFO ..

Popular posts from this blog

Step by step guide on how to pay Income Tax that is due

Rajiv Gandhi Equity Savings Scheme