flag[i] = 1;
while (flag[j])
{
if (turn == j)
{
flag[i] = 0;
while(turn == j)
;
flag[i] = 1;
}
}
/* enter C.S. */
/* exit C.S. */
turn = j;
flag[i] = 0;
This algorithm is called Dekker's solution.
j = a++;
// execute in one atomic operation
a = 0;
Either come up with a solution to the C.S. problem using this facility or show that it cannot help.
#include "Exception.h"
#include "Semaphore.h"
#include <iostream.h>
const MaxStackSize = 100;
class Stack
// throws an exception object when popping an empty stack, and when pushing
into a full stack
{
private:
int s[MaxStackSize];
int stackp;
// stack pointer
Exception * e;
// For error handling
Semaphore * sem;
// For mutual exclusion
public:
Stack();
~Stack()
{};
int Pop(void);
void Push(int item);
};
Stack::Stack()
{
stackp = MaxStackSize;
e = new Exception();
sem = new Semaphore(1);
}
int Stack::Pop(void)
{
P(sem)
if(stackp == MaxStackSize)
{
e->SetErrorMsg("Popping empty stack");
e->SetErrorLocation("Stack::Pop()");
throw(e);
}
V(sem);
return s[stackp++];
}
void Stack::Push(int item)
{
P(sem)
if(stackp == 0)
{
e->SetErrorMsg("Pushing to a full stack");
e->SetErrorLocation("Stack::Push()");
throw(e);
}
s[--stackp] = item;
V(sem);
}