Sunday, March 22, 2009

Ch8, Ex9

The new monitor supports only two operations, lock and newcondition. lock is same and newcondition gives a new condition variable which supports two operations wait and notify.

I. Buffer reimplementation
class Buffer
attr m buf first last n i nonempty nonfull
meth init(N)
m:={NewMonitor}
buf:={NewArray 0 N-1 null}
n:=N i:=0 first:=0 last:=0
nonempty := @m.newcondition
nonfull := @m.newcondition
end
meth put(X)
{@m.'lock' proc {$}
if @i>=@n then
{@nonfull.wait}
{self put(X)}
else
@buf.@last:=X
last:=(@last+1) mod @n
i:=@i+1
{@nonempty.notify}
end
end}
end
meth get(X)
{@m.'lock' proc {$}
if @i==0 then
{@nonempty.wait}
{self get(X)}
else
X=@buf.@first
first:=(@first+1) mod @n
i:=@i-1
{@nonfull.notify}
end
end}
end
end

II. Monitor Reimplementation
fun {NewMonitor}
L={NewGRLock}
proc {LockM P}
{L.get} try {P} finally {L.release} end
end
fun {NewCondition}
Q={NewQueue}
proc {WaitM}
X in
{Q.insert X} {L.release} {Wait X} {L.get}
end
proc {NotifyM}
U={Q.deleteNonBlock} in
case U of [X] then X=unit else skip end
end
in
c(wait:WaitM notify:NotifyM)
end
in
monitor('lock':LockM newcondition:NewCondition)
end

No comments:

Post a Comment