CS 3204: Synchronization Example
Problem description
-
3 types of processes: A, B, C
-
Critical Resource: T
-
Criteria:
-
ME B & C
-
ME A & C
-
ME among the As
-
ME among the Cs
-
Cs have priority over As and Bs
Monitor Solution
ABC: Monitor
var Aok, Bok, Cok: Condition;
WC, WB, RB: Integer <-- 0;
ABusy, CBusy: Boolean <-- FALSE;
ReqA
if (WC > 0 || ABusy || CBusy)
Aok.wait;
ABusy = TRUE;
|
RelA
ABusy = FALSE;
if (WC == 0)
Aok.signal
else if (RB == 0)
Cok.signal;
|
ReqB
if (WC > 0 || CBusy) {
WB++;
Bok.wait;
WB--;
}
RB++;
|
RelB
RB--;
if (RB == 0 && !ABusy) {
Cok.signal;
}
|
ReqC
if (RB > 0 || CBusy || ABusy) {
WC++;
Cok.wait;
WC--;
}
CBusy = TRUE;
|
RelC
CBusy = FALSE;
if (WC > 0) {
Cok.signal;
else {
Aok.signal;
while (WB > 0)
Bok.signal;
}
|
Semaphore Solution
var MEAC, MEBC, MEC: Semaphore <-- 1;
semWC, semWB, stopA, stopB: Semaphore <-- 1;
WC, WB: integer <-- 0;
Process A
P(stopA); // For C's priority
V(stopA);
P(MEAC); // For ME between A C
<CS>
V(MEAC);
|
Process B
P(stopB); // For C's priority
V(stopB);
P(semWB);
WB++;
if (WB == 1)
P(MEBC); // For ME between BC
V(semWB);
<CS>
P(semWB)
WB--;
if(WB == 0)
V(MEBC);
V(semWB);
|
Process C
P(semWC); // for updating WC
WC++;
if (WC == 1) {
P(stopB); // C's priority over B
P(stopA); // C's priority over A
P(MEBC); // ME between C B
P(MEAC); // ME between A C
}
V(semWC);
P(MEC);
<CS>
V(MEC);
P(semWC);
WC--;
if (WC == 0) {
V(stopA);
V(stopB);
V(MEAC);
V(MEBC);
}
V(semWC);
|