Reputation: 186
I'm trying to implement the pseudo solution below in java as part of an assignment. The pseudo is for a Readers Preference program, specifically the reader process itself. There is an accompanying writer process, but to keep things spartan I didn't bother pasting it.
Process Reader[i=1 to M] {
while (true) {
/* Implementing <await (nw == 0) nr = nr+1;> */
P(e);
if (nw > 0) {dr = dr+1; V(e); P(r);}
nr = nr + 1;
if (dr > 0) {dr = dr-1; V(r);}
else V(e);
read the database;
/* Implementing <nr = nr-1;> */
P(e);
nr = nr - 1;
if (nr == 0 and dw > 0) {dw = dw-1; V(w);}
else V(e);
}
}
Originally I assumed that the line:
/* Implementing <await (nw == 0) nr = nr+1;> */
Was some kind of commenting on what was occurring, but having just re-read it I think it's supposed to be an if statement to control the P(e) locking semaphore. Below is what I've implemented in my code based on the above assumption.
if (nw == 0) {
nr = nr++;
try {
e.acquire();//P(e)
} catch (InterruptedException e) {
}
}//end if
The output from the rest of the code has been a bit of a mess, but it seems to work. I used delays with a thread.sleep in order to make the output to console more readable and again it seemed ok, though I was wary about using delays as that seemed quite likely to interfere with the results, since I was giving the writer processes a longer delay. In theory though, the locking system should be sound and the delays should just make the output to console more readable.
So, am I correct to use the if statement above?
Can you give me any tips on outputting data to the console to prove it works as it should (readers preference/writers preference)
Upvotes: 1
Views: 1029
Reputation: 186
The line
/* Implementing <await (nw == 0) nr = nr+1;> */
is an atomic process, the code below carries that out atomically.
If anyone was interested about the other question, just add print statements under the acquire/release.
Upvotes: 0