Assume this problem: 2 programs, A and B, 1 process of A, M processes of M, 1 shared variable named var
A
main(){
int i, a[50];
for(i=0;i<50;i++)
var = a[i];
}
B
main(){
int i, b[50];
for(i=0;i<50;i++)
b[i] = var;
}
Now, what I need to do is make sure that for each loop in A, each of the M B-processes read the shared variable (once!) and store it in their arrays. So in the end each B-process will have a copy of the a-array in their b-arrays. This is a semaphore problem, and the solution can be in pseudocode, so language is irrelevant.
An initial solution which isn't working: I'm using a semaphore B initialized at 0, and each time A writes something, i'm increasing B by M, and doing a down(A). At the begining of each B loop I do a down(B). Then in the end of each loop of B, I check wether M readers have read and stored var, and if they have, I'm doing up(A).
Obviously the above lets a single B process "consume" all the M uses that were supposed to be spread through the M readers. So how do I - intelligently - make sure that each B will read each var only once? An array of M semaphores, one for each M, would do the job but it's most likely not what the exercise is asking for.