Monitor eu
{
const int Urgent = 1;
int Code;
condition doctor, patient[2];
queue doctorName, patientName[2];
Name getdoctor(Name name, int code)
{
patientName[code].enqueue(name);
if ((code == Urgent && doctorName.Count == 0) || (code != Urgent && doctorName.Count < 4))
patient[code].wait();
else
{
Code = code;
doctor.signal();
}
return doctorName.dequeue();
}
Name getpatient(Name name)
{
doctorName.enqueue(name);
if (patientName[Urgent].Count == 0 && (patientName[1 - Urgent].Count == 0 || doctorName.Count < 4))
doctor.wait();
else
{
Code = (patientName[Urgent].Count > 0)? Urgent : 1 - Urgent;
patient[Code].signal();
}
return patientName[Code].dequeue();
}
}
/* If (1) e (2) share the same expressive power than
I may implement (1) by means of (2) and vice versa. */
// (1) by means of (2)
void send2(Message m1, Message m2, Pid d1, Pid d2)
{
asend(<SND, getpid(), d1, d2>, server);
asend(m1, arecv(server));
asend(m2, arecv(server));
}
Message receive2()
{
asend(<RCV, getpid(), NULL, NULL>, server);
return arecv(*);
}
Process server()
{
DataBase dbSnd, dbRcv;
while (true)
{
<flag, src, d1, d2> = arecv(*);
if (flag == RCV)
{
<sender, d1, d2> = dbSnd.remove(<?, src, ?> || <?, ?, src>);
if (sender)
{
asend(src, sender);
if (d1 == src)
d1 == NULL;
else
d2 == NULL;
if (d1 || d2)
dbSnd.insert(<sender, d1, d2>);
}
else
dbRcv.insert(src);
}
else
{
if (dbRcv.remove(d1))
{
asend(d1, src);
d1 = NULL;
}
if (dbRcv.remove(d2))
{
asend(d2, src);
d2 = NULL;
}
if (d1 || d2)
dbSnd.insert(<src, d1, d2>);
}
}
}
// (2) by means of (1)
void asend(Message msg, Pid dst)
{
send2(<SND, getpid(), dst, msg>, NULL, server, NULL);
}
Message arecv(Pid sender)
{
send2(<RCV, getpid(), sender, NULL>, NULL, server, NULL);
return arecv(server);
}
Process server()
{
DataBase dbRcv, dbSnd;
while (true)
{
<flag, p1, p2, msg> = receive2();
if (flag == RCV)
{
<, , msg> = dbSnd.remove(<p2, p1, ?>)
if (msg)
send2(msg, NULL, p1, NULL);
else
dbRcv.insert(<p1, p2>);
}
else
{
if (dbRcv.delete(<p2, p1>))
send2(msg, NULL, p2, NULL);
else
dbSnd.insert(<p1, p2, msg>);
}
}
}