How would you complete this scheme and how many semaphores would you use to obtain
a) ABCD ACBD sequence
b) ABCD ABDC sequence
using these two processes (consider using pseudocode es: wait(s1) signal(s1) etc…)
Process 1
P1:while(1){
.
printf("A");
.
.
printf("C");
.
}
Process 2
P2:while(1){
.
printf("B");
.
.
printf("D");
.
}
Consider the dots as places where the missing code(primitives) could be inserted
@Jerry
After some internet researching I think I’ve got my first point (a) solved,
the solution would be to build a precedence graph like this
A<--(s0)--^
/ \ |
(s1)-- --(s2) |
(me)------- |
/ \ |
B C |
\ / |
-------(s3) |
\ / |
D-------->|
with INIT(s0)=INIT(ME)=1
and INIT(s1)=INIT(s2)=INIT(s3)=0
therefore I’d have P1
P1:while(1){
wait(s0);
printf("A");
signal(s2);
signal(s1);
wait(s1);
wait(ME);
printf("C");
signal(ME);
signal(s3)
}
and P2
P2:while(1){
wait(s2);
wait(ME);
printf("B");
signal(s3);
signal(ME);
wait(s3);
wait(s3);
printf("D");
signal(s0)
}
Do you think my approach is right ?, could I reduce more the number of semaphores used ?
(for now there are 5 (2 mutex and 3 normal))
I do think your approach with a precedence graph is correct, but the
problem statement is a bit unclear, for example, from the graph is
looks like
BandCcan occur in any order, but no indication ofthis in the original a) and b) sequences.
(EDIT: it become clear that
BandChave to alternate)So, for case a) the following (infinite)
sequence is acceptable:
AprecedesBby program logic and they are in the same thread.Likewise
CprecedesDfor the same reasons. Hence, semaphores are needed to enforce precedence only along the edgesA->C,B->DandD->A. The edge betweenBandCchanges direction each cycle, hence we need an additional bit of state, to determine the direction:B->CorB<-CIt can be done with an extra variable, or we can maintain the state implicitly by duplicating the loop bodies, like below:I will leave you to implement b) by yourself 🙂