I wrote a program to set up the Producer/Consumer relationship and right now it is not synchronized and I want to implement Semaphores but I am having trouble with it. I want the producer/consumer threads to behave like this:
Java Code
Producer Thread:
void main()
{
int nextValueProduced; //variable to store value produced
while (!done)
{
nextValueProduced = generateTheValue(); //produce value
P( valueconsumed); //wait until value is consumed
sharedValue = nextValueProduced;
V( valueProduced);
}
}
Consumer Thread:
void main()
{
int nextValue; //variable to store consumed
while (!done)
{
P( valueProduced); //wait until value is produced
nextValueConsumed = sharedValue;
V( valueConsumed); //signal value has been consumed
processTheValue( nextvalueconsumed);
}
}
This is what I have now for the producer thread:
Java Code
public class Producer extends Thread{
private Buffer sharedLocation;
public Producer (Buffer shared) {
super("Producer");
sharedLocation = shared;
}
public void run() {
for (int count = 1; count <= 4; count++){
try {
Thread.sleep((int) (Math.random() * 3001));
value
//check to see if the value has been consumed P( valueConsumed );
sharedLocation.set(count);
//let consumer thread know it can consume the value
}
catch (InterruptedException exception) {
exception.printStackTrace();
}
}
System.err.println(getName() + " done producing.");
}
}
The consumer thread:
Java Code
public class Consumer extends Thread{
private Buffer sharedLocation;
public Consumer (Buffer shared) {
super("Consumer");
sharedLocation = shared;
}
public void run() {
int sum = 0;
for (int count=1; count<=4; count++) {
try{
Thread.sleep((int) (Math.random() * 3001));
sum += sharedLocation.get();
}
catch (InterruptedException exception) {
exception.printStackTrace();
}
}
System.err.println(getName() + " done consuming. and sum= " + sum);
}
}
This is what I have currently for semaphore:
Java Code
public class Semaphore{
private int sharedValue;
Semaphore valueProduced = new Semaphore(0);
Semaphore valueConsumed = new Semaphore(1);
void get(){
try {
/*public class Semaphore {
private int value;
public Semaphore() {
value = 0;
}
public Semaphore (int initial) {
value = initial;
}
public void P() {
wantToEnterCS();
// Use any viable busy-waiting mutex solution
while (value == 0)
{
finishedInCS();
wantToEnterCS();
}
value --;
finishedInCS();
}
public void V() {
wantToEnterCS();
value++;
finishedInCS();
}
}