HOMEWORK Add in variable S to unoptimized version so that 1. Outside P and V S is accurate, i.e. when no process is in P or V, S = k -#P + #V 2. S >= 0 always Note: NS satisfies 1 but not 2. Remind me to go over this next class These solutions all employ binary semaphores. Hence if N tasks try to execute P/V on the COUNTING semaphore, there will be a part that is serialized, i.e. will take time at least proportional to N. Fetch-and-add An NYU invention Reference Gottlieb, Lubachevsky, and Rudolph, TOPLAS, apr 83 Good name (like fetch-and-or test-and-set) fetch-and-add (in out X, in e) is oldX <-- X X <-- X+e return oldX Assume this is an atomic operation NYU built hardware that this did this atomically Indeed could do N FAAs in the time of 1. Interesting work ... but this is not a hardware course Some hardware description in TOPLAS better in IEEE Trans. Comp. Feb 83 Just as test-and-set seems perfect for binary semaphores, fetch-and-add seems perfect for counting semaphores. NaiveP (in out S) is V (in out S) is while FAA(S,-1) <= 0 FAA(S,+1) FAA(S,+1) Explain why it works. But it fails!! Why? Give history (dijkstra, wilson) P (in out S) is V (in out S) is L: while S<=0 FAA(S,+1) if FAA (S,-1) <= 0 FAA(S,+1) goto L If you don't like gotos and labels, you can rewrite P as ElegantP (in out S) is while S<=0 if FAA (S,-1) <= 0 FAA(S,+1) ElegantP(S) A "good" compiler will turn out the identical code for P and ElegantP "Good" means capable of elimnating TAIL RECURSION, but ... This is not a programming languages course This is not a compilers course The real P looks VERY close to NaiveP, especially if you rewrite NaiveP as AlternateNaiveP (in out S) is L: if FAA (S,-1) <= 0 FAA(S,+1) goto L So all that P adds is the while loop But the test in the while is "redundant" as the next if makes the same test Explain why (real) P and V work. First show that the previous problem is gone. Mutual exclusion because any process in CS found S positive Progress a little harder to show Idea is to look at all states of the system and show that once you get to a state where a process has reached P, then any process in the CS can leave and then at least one trying process can get in. See the TOPLAS article for a proof HOMEWORK 2.8 If you believe the claim that concurrent FAA can be executed in constant time (really it takes the time of one shared memory reference, which must grow with machine time), then the counting semaphore is a constant time operation with P/V (assuming the semaphore is wide open). We gave this "redundant" test a name test-decrement-retest or TDR We can apply this TDR technique/trick to the bad soln we began with (the one using one binary semaphore). Binary semphore q initially open P (in out S) is V (in out S) is L: While S <= 0 P(q); S++; V(q) P(q) if S > 0 S-- V(q) else V(q goto L