Producer-Consumer

Producer-consumer function using semaphore

by scotp71

HTML

<h1>
Producer-Consumer
</h1>
<br/>
Enter data and click 'Create Data' button to add to buffer.
<br/>
Click 'Consume' to remove data from the buffer,
<br/>
<br/>
Add as much data as you want, unless the buffer is full,
<br/>
<br/>
<br/>


<input type="textbox" id="v" value="" />
<input type="button" value="Create Data" onclick="addToBuffer()"/>

<br/>
<br/>
<input type="button" value="Consume" onclick="consumeData()"/>
<p id="out"></p>
<div id="output2"></div>

JavaScript

/*
4610 Programming Assignment 4
Producer-Consumer Function using semaphores
Written by: Scot Pfeffer
4/16/19
*/

function LinkedList(){
	this.first = null;
  this.last = null;
  this.length = 0;
}

function Node(){
	this.next = null;
  this.prev = null;
  this.content = null;
}

//adds to the buffer/queue and increments/decrements semaphores
LinkedList.prototype.enqueue = function(_content) {
	var node = new Node();
  node.content = _content;
  if(this.first == null) {
  	this.first = node; 
    this.last = node;
    this.length = 1;
    fillCount++;
    emptyCount--;
    return node;
  }
  else if(this.first != null){
  	this.last.prev = node;
    node.next = this.last;
    this.last = node;
    this.length++;
    fillCount++;
    emptyCount--;
    return node;
  }
}

//removes from the buffer/queue and increments/decrements semaphores
LinkedList.prototype.dequeue = function(){
while(this.first!=null){
	var node = new Node();
  node = this.first;
  this.first = this.first.prev;
  this.length--;
  fillCount--;
  emptyCount++;
  return node.content;
}
return;
}

//global variables for the queue and semaphores
var Q1 = new LinkedList();
var fillCount = 0;
var emptyCount = 5;

//function to add data to the buffer after checking semaphore
function addToBuffer(){
	var textData = document.getElementById("v").value;
	 if (emptyCount < 1){
  	print("Cannot add " + textData + ". The buffer is full.  Consume to open more space!");
  }
  if (emptyCount > 0){
  	Q1.enqueue(textData);
    print("Your data has been added: " + textData);
  }
}

//function to remove data from the buffer after checking semaphore
function consumeData(){
  if (fillCount < 1){
  	print("The buffer is empty.  Create more data!");
  }
  if (fillCount >0){
  	var consumeText = Q1.dequeue();
    print("Here is your data: " + consumeText + " <br/>Click 'Consume' again if you want more.");
  }
}

function print(t){
	document.getElementById("out").innerHTML += t + " <br/> ";
}