INF 4140: Models of Concurrency Series 4

Size: px
Start display at page:

Download "INF 4140: Models of Concurrency Series 4"

Transcription

1 Universitetet i Oslo Institutt for Informatikk PMA Olaf Owe, Martin Steffen, Toktam Ramezani INF 4140: Models of Concurrency Series 4 Høst Topic: Monitors (Exercises with hints for solution) Issued: Exercise 1 (From the book) Solve: 5.2, 5.3, 5.7, 5.8 Remark: it may be hard to get all the signaling details of 5.7b) right. However, you should try to describe the waiting conditions for each kind of process. For 5.8c): Only describe the changes you need to do, any actual programming is not necessary. Do you need any additional data-structure? If yes, how should this structure be manipulated? Exercise 2 (Signalling disciplines[?, Exercise 5.2]) Is the monitor in [?, Figure 5.6, page 217] correct under signal-and-wait? 1 monitor Shortest Job Next { 2 bool f r e e = true ; 3 cond turn ; 4 5 procedure r e q u e s t ( int time ) { 6 i f ( f r e e ) 7 f r e e := f a l s e 8 else 9 wait ( turn, time ) 10 } procedure r e l e a s e ( ) { 13 i f (empty( turn ) ) 14 f r e e := true ; 15 else 16 signal ( turn ) ; 17 } Solution: [of Exercise 2] The code is used in the book to illustrate a non-fifo waiting discipline (more precisely, priority waiting) and the use of a correspondingly more general wait-operation. The original code for semaphores [?, page 211] which closesly resembles the problem here (with priority queues) was used to illustrate the passing the condition technique. This pattern is typically used for the weaker signalling technique signal-and-continue. The solution is correct with the signal-and-wait discipline. In fact, with signal-and-wait the program may be simplified to the code of Listing 1 (see the next Exercise 3). The simplification is in the release-procedure (but also the request is slightly changed: free is set to falses unconditionally)

2 Exercise 3 (Signalling disciplines and SJN [?, Exercise 5.3]) Consider the code of Listing 1. 1 monitor Shortest Job Next { 2 bool f r e e = true ; 3 cond turn ; 4 5 procedure r e q u e s t ( int time ) { 6 i f ( f r e e ) wait ( turn, time ) ; 7 f r e e := f a l s e ; 8 } 9 procedure r e l e a s e ( ) { 10 f r e e := true ; 11 signal ( turn ) ; 12 } 13 } Listing 1: SJN Does it work for signal-and-continue? How about signal-and-wait? Solution: [to Exercise 3] The solution works with signal-and-wait since execution control is handed directly to the signaled process. With signal-and-continue however, the solution may fail since there is an arbitrary delay between signaling and execution of the signaled process. The resource may be occupied when the awakened process starts execution. Note in that context: requests may enter jumping over the wait-statement in the condition in the request procedure (which is the reason what the described violation happens). If all requests would call wait first, situation would be different. Remember: wait (unlike semaphores unconditionally put a process into a corresponding queue (namely the queue of the condition variable). For a solution, the discussion around the monitor implementations for semaphores should be consulted (where the lecture discussed S&W vs S&C), and furthermore discussed that for S&W the code can be simplfied wrt. the original formulation using a while-loop. This simplfication using conditional corresponds to the code of Listing 1 (which works only for S&W as explained in the lecture). Exercise 4 (One lane bridge [?, Exercise 5.7, page 256]) The one-lane bridge is a classical synchronization problem. Solve the problem with a signal-and-continue monitors. Give a useful invariant. provide a solution which assures fairness. Solution: [of Exercise 4] a) As for the readers/writers problem, we cannot encapsulate the shared resource (the bridge) in the monitor since that would disallow several cars going in the same direction. That is similar to what we had in the lecture about the readers/writers problem for instance. Instead, we assume that travelling south is initiated by an invocation of go-south and ended by an invocation of end-south. Accordingly for traveling north. This solution is not fair. 1 monitor Bridge { 2 int ns = 0 ; # number o f cars going south 3 int nn = 0 ; # number o f cars going north 4 cond gosouth gonorth ; 5 ## I n v a r i a n t : 2

3 6 ## (ns = 0 nn = 0) 7 ## (ns > 0 => empty(gosouth)) (nn > 0 => empty(gonorth)) 8 9 # c a l l e d by cars wanting to go north 10 procedure go north ( ) { 11 while ( ns > 0) wait ( gonorth ) 12 nn := nn } 14 # c a l l e d by cars f i n i s h e d going north 15 procedure end north ( ) { 16 nn := nn 1 ; 17 i f ( nn = 0) s i g n a l a l l ( gosouth ) ; 18 } # c a l l e d by cars wanting to go south 21 procedure go south ( ) { 22 while ( nn > 0) wait ( gosouth ) 23 ns := ns } 25 # c a l l e d by cars f i n i s h e d going south 26 procedure end south ( ) { 27 ns := ns 1 ; 28 i f ( ns = 0) s i g n a l a l l ( gonorth ) ; 29 } 30 } Remark: The solution follows the standard while-not-invariant-wait pattern (which is typical for a signal-and-continue scheme). A solution using an if only would not work for signal-and-continue. It s important to understand this. Once there was a discussion, in that the code looks perhaps like the one for passing the condition and that lead to the impression that the code would work also without while-loop, just with an if even in a S&C setting (as is the case with the passing the condition ). Here is the fake i.e., wrong argument while an if would also work: the signalling is done only at the end of the critical section, and it s done only if it s guaranteed that the condition on which it is signalled is true. Therefore we don t need a while-loop. One should be careful here: The code is not analogous to passing or forwarding the condition in the way we have learnt when implementing P and V via monitors. In a passing the condition solution, the signaller, before doing the actual signal, already sets the condition to the state that the processes waiting on the condition variable would set when they enter. This is not done here. If a south-going car leaves the bridge, when passing the condition, it should not just update the part of the condition that concerns the car itself (i.e., decreasing ns) but also take care of cars that are waiting on a condition variable. More precisely, it takes care of all those cars (processes) that it will wake up by sending them a signal. In the passing-the-condition pattern, that s the signallers responsibility and that allows in the code of the receiver of that signals, to not recheck the condition again, i.e., the while loop can be replaced by a conditional. Note that for processes in the entry queue, no such passing can be done, since first one cannot signal them and secondly, one can also not check if someone is in the entry queue (unlike for checking the queue on a 3

4 condition variable). The latter is also necessary, without being able to check whether the queue on a condition variable is empty, passing-the-condition does not work. Part of the condition which conceptually was forwarded was that the semaphore counter was not increased in the case of a V (which means dually that P did not incease it. The counter in the P and V monitor are somehow the boolean condition (not the condition variable) that governs the entry to the monitor. This is the condition which is said to be forwarded from one process to the other. In the solution here, where ns and nn somehow are the core of the condition, this kind of passing is not done. In the P and V monitor, it furthermore required a check that the queue of the condition variable was empty. Finally, there, the forwarding-the-condition guaranteed a FIFOsemaphore (and it was not done with while, but with if. Perhaps one could make a passing the condition solution. That would mean: at the end of the, say, south-going procedure, the procedure 1. determines how many cars are waiting on the condition, 2. sets the nn to that number (and decrease the ns) 3. and do a signal all. That would guarantee that no south-going could sneak in. That s done by the last solution here (Listing 4) b) We have seen that sneaking is (mainly) a consequence of jumping the queue, since a free monitor allows processes to enter without queuing up. In terms of the cars: north-going cars may thus just enter disegarding the fact that there are cars northgoing cars in the entry queue, which are thus neglected. One attempt for a solution is: before executing go north for real, check if there are n-cars in the entry queue. Since we have no ways to check the entry queue, 1 one needs to program some appropriate variables oneself. Here we count the number of delayed cars (separate for north and south). Cars going in one direction are delayed if someone wants to go in the other direction. We use additional counters to count the number of delayed processes. We can no longer use loops for testing waiting conditions since these do not prevent sneaking. 2 The difference between the while-loop and the conditional solution is: in the while loop solution, when being woken up, it s not guaranteed that the enter-procedure is already successful because it has to try again. In the conditional-solution, being signalled means: being on the rope (because the number is increased immediately afterwards). Instead, we signal a process only when we know that it can continue. A first attempt may be: 1 monitor FairBridge { Listing 2: Fair bridge, first attempt 2 int ns = 0 ; # number o f cars going south 3 int nn = 0 ; # number o f cars going north 4 int ds = 0 ; # number o f delayed cars wanting to go south 5 int dn = 0 ; # number o f delayed cars wanting to go north 6 cond gosount gonorth ; # as b e f o r e 7 8 procedure go north ( ) { 9 i f ( ( ds > 0) ( ns > 0) { 10 dn := dn + 1 ; 1 We learnt syntax to check the queue of condition variables, though, 2 Perhaps the argument is imprecise: a solution with loops + unconditional signalling does not prevent sneaking. This code here is a hybrid-solution: selective signalling but nonetheless a while-loop. 4

5 11 wait ( gonorth ) 12 dn := dn 1 ; 13 } 14 nn := nn + 1 ; 15 } procedure end north ( ) { 18 nn := nn 1 ; 19 i f ( nn = 0) s i g n a l a l l ( gosouth ) 20 } procedure go south ( ) { 23 i f ( ( dn > 0) ( nn > 0 ) ) { 24 ds := ds + 1 ; 25 wait ( gosouth ) ; 26 ds := ds 1 ; 27 } 28 ns := ns + 1 ; 29 } procedure end south ( ) { 32 ns := ns 1 ; 33 i f ( ns = 0) s i g n a l a l l ( gonorth ) 34 } 35 } However, there is one subtle problem with this code. Assume that two processes are waiting on gosouth when nn becomes zero, i.e., when the last car going north leaves the bridge: the last leaving care then executes signal all(gosouth). Note that the waiting two south-going processes have executed ds := ds + 1 before going into the waiting state. That means, north-going processes cannot enter but have to wait themselves (which is fine and as intended). Now, assuming that dn > 0 (i.e., there has been then a north-going attempt), only the two awakened south-bound processes can continue. Assume that one of the processes finishes both the execution of go-south as well as end-south() before the second process starts to execute the rest of go-south. The end south, however, signals gonorth, which means that cars is allowed to go north. Afterwards, the second process (which had been given access via signal-all) may finish go-south(). This breaks the central invariant A traffic accident occurs... nn = 0 ns = 0! (1) One solution is to have an additional variable ensuring that no such signaling is done before all awakened processes has started up: 1 monitor FairBridge { Listing 3: Fair bridge 1 2 int ns = 0 ; # number o f cars going south 3 int nn = 0 ; # number o f cars going north 4 int ds = 0 ; # number o f delayed cars wanting to go south 5 int dn = 0 ; # number o f delayed cars wanting to go north 6 int s t a r t u p = 0 ; # a d d i t i o n a l v a r i a b l e 7 cond gosount gonorth ; 8 9 procedure go north ( ) { 5

6 10 i f ( ( ds > 0) ( ns > 0) { 11 dn := dn + 1 ; 12 wait ( gonorth ) 13 dn := dn 1 ; 14 s t a r t u p := s t a r t u p 1 ; 15 } 16 nn := nn + 1 ; 17 } procedure end north ( ) { 20 nn := nn 1 ; 21 i f ( nn = 0 s t a r t u p = 0) { # s i g n a l only i f a l s o s t a r t u p i s 0 22 s t a r t u p := ds ; # remember a l l 23 s i g n a l a l l ( gosouth ) 24 } 25 } procedure go south ( ) { 28 i f ( ( dn > 0) ( nn > 0 ) ) { 29 ds := ds + 1 ; 30 wait ( gosouth ) ; 31 ds := ds 1 ; 32 s t a r t u p := s t a r t u p 1 ; 33 } 34 ns := ns + 1 ; 35 } procedure end south ( ) { 38 ns := ns 1 ; 39 i f ( ns = 0 s t a r t u p = 0) { # s i g n a l only i f a l s o s t a r t u p i s 0 40 s t a r t u p := dn ; 41 s i g n a l a l l ( gonorth ) ; 42 } 43 } 44 } Another possible solution is to count up ns in end-north and nn in end-south, executing a while loop in these procedures to start up each delayed process. Also, ds and dn are no longer needed since it suffices to test if there are any delayed processes which can be done by empty: 1 monitor FairBridge2 { Listing 4: Fair bridge 2 (forwarding-the-condition) 2 int ns = 0 ; # number o f cars going south 3 int nn = 0 ; # number o f cars going north 4 cond gosouth gonorth ; 5 6 procedure go north ( ) { 7 i f ( ns > 0! empty( gosouth ) ) { 8 wait ( gonorth ) ; 9 } else {nn := nn + 1 ; } 10 } procedure end north ( ) { 13 nn := nn 1; 14 i f ( nn = 0) { 15 while (! empty( gosouth ) ) { 16 ns := ns + 1 ; 6

7 17 signal ( gosouth ) ; 18 } 19 } 20 } procedure go south ( ) { 23 i f ( nn > 0! empty( gonorth ) ) { 24 wait ( gosouth ) ; 25 } else { ns := ns + 1 ; } 26 } procedure end south ( ) { 29 ns := ns 1 ; 30 i f ( ns = 0) { 31 while (! empty( gonorth ) ) { 32 nn := nn + 1 ; 33 signal ( gonorth ) ; 34 } 35 } 36 } 37 } Remark: Sneaking Here s a short explanation what is meant when saying processes are sneaking in. Basically what is meant is that there s a violation of the FIFO property, i.e., processes jump the queue. This is a phenomenon that is typical for solutions like the one from Listing (with signal-and-continue and a while-pattern at the entry ). The sneaking is ultimately a consequence of the fact that there are two queues involved (and the way S&C works): If a process is waiting on a condition variable and is being signalled, it will be put into the entry queue. That s insofar ok, but we have to look at the fine-print of the monitor behavior. The semantics, as described by [?] is as follows. A process that invokes a monitor procedure will jump the entry queue if the monitor is currently free! That s what s meant by sneaking in. In the bridge-example code (and without doing passing-the-condition): the last south-going care puts all northgoing cars to the entry queue. At that point, the monitor is free, and the northging cars have not yet set the number nn > 0 (since they are not yet in the monitor). That s the window of vulnerabilty, where another completely new northgoind care could just go in (likewise a southgoing car, but that seems less unfair ). Exercise 5 (Savings account [?, Exercise 5.8]) A savings account contains as main internal state the balance, which is not allowed to become negative. Provide a monitor solution to that problem, start by specifying the invariant. Make a first-come-first-serve solution. Assume a function amount(cv) Make a fcfs-solution without that function available. Solution: [of Exercise 5] a) We present a simple solution using covering condition. This one shows a standard monitor pattern very clearly. The only procedure that has a synch-need is the withdrawprocedure. Therefore, at the beginning, there s a while-loop containing a wait on the negation of invariants. The condition is of course not the literal negation of the invariant, but it s formulated in a way, like while the invariant is not satisfied, if I do the next balance := balance amount, do a while-wait-loop. 7

8 1 monitor Account ( ) { 2 Listing 5: Bank account 3 int balance = 0 ; # c urrent balance ; I n v a r i a n t : balance 0 4 cond cv ; 5 6 procedure d e p o s i t ( int amount ) { 7 balance := balance + amount ; 8 # Covering c o n d i t i o n : someone can maybe continue ; s i g n a l a l l. 9 s i g n a l a l l ( cv ) ; 10 } procedure withdraw ( int amount ) { 13 while ( amount > balance ) wait ( cv ) ; 14 balance := balance amount ; 15 } 16 } b) In order to follow the FCFS principle, we have to prevent sneaking. In principle, especially the signal-and-continue discipline in itself does not guarantee fifo or fcfs disciplines. But the first observation should be clear: what we cannot do is use signal all. Thefore, we must use signal. Since deposit needs not to wait, the signalling is only for processes waiting to do the withdrawal. Let s start thinking of what/when/how the deposit-function should signal. For that, the amount-function is helpful, because the deposit should only signal if the first one in the queue does not want to withdraw too much. 3 A similar condition for signalling could be done at the end of the withdraw-precodure. That alone, however, won t do the job. The problem is a bit like the signal-all, namely what it may happen that more than one withdraw-procees is woken up in the signal-andcontinue discipline. That can happen if deposit happens to sucessfully execute two times in a row. When a withdrawal starts execution, it cannot simply test if the waiting queue is empty or not, since there may exist awakened processes that have not gained execution control yet. We use a boolean variable wait to indicate the existence of such processes. Listing 6: First-come-first-serve 1 monitor FCFSAccount ( ) { 2 int balance = 0 ; # c urrent balance 3 bool waiting = f a l s e ; 4 cond cv ; # FIFO queue 5 ## I n v a r i a n t : balance procedure d e p o s i t ( int amount ) { 8 balance := balance + amount ; 9 i f ( (! empty( cv ) ) 10 ( headamount ( cv ) balance ) ) # make use o f amount f u n c t i o n 11 signal ( cv ) ; 12 } procedure withdraw ( int amount ) { 15 i f ( waiting ( amount > balance ) ) { 16 waiting := true ; 17 wait ( cv ) ; 3 The check that the queue is not empty is not too important, logically. One could also arrange that the amount function is defined approriately for an empty queue. 8

9 18 } 19 balance := balance amount ; 20 i f (empty( cv ) ) 21 then waiting := f a l s e ; 22 else i f ( headamount ( cv ) balance ) // make use o f amount f u n c t i o n 23 then signal ( cv ) ; 24 } 25 } deposit only awakens the first waiting withdrawal if this withdrawal can continue. At the end of withdraw, we therefore awaken the next waiting process if it can continue. (For instance, if we deposit $600, it is safe to withdraw $300 twice.) Remark 1 (Forward-the-condition) The solution is not really a forwarding-the-condition solution. It is simular to one of the fair-bridges solutions before. FTC would require not just to be able to check the amount with headamount but also already to reduce it. The use of the variable waiting is similar to the use of delayed cars before. Remember also that the interim solution from Listing 2 had an error. It seems that this error would not occur here, not even with a signal-all, because there, the problem was that the interaction for instance going north consisted of two procedures and that one process would complete both of them before the other one starts. That s not the case here. c) We need an additional data structure to remember the different amounts associated with the different waiting withdrawals. We can for instance use a queue q of integers, and program according to the following principle: For a process p waiting in position n in the queue on cv, the nth value on q is the amount of p. An alternative to avoid the data structure is to use an additonal condition variable, delaying at most one process, and to record the amount of this process by an integer variable: 1 monitor FCFSAccount2 { 2 int balance = 0 ; 3 bool wait = f a l s e ; 4 cond cv ; 5 int aw ; # amount o f f i r s t w a i t i n g withdrawal 6 cond fw ; # used to d e l a y f i r s t w a i t i n g withdrawal 7 ## I n v a r i a n t : balance >= 0 && ( empty ( fw ) &&! wait ) => empty ( cv ) 8 9 procedure d e p o s i t ( int amount ) { 10 balance = balance + amount ; 11 i f ( (! empty( fw ) ) && ( balance >= wa ) ) signal ( fw ) ; 12 } procedure withdraw ( int amount ) { 15 i f ( wait ) wait ( cv ) ; 16 i f ( balance < amount ) { 17 wait = true ; 18 wa = amount ; 19 wait ( fw ) ; 20 } 21 balance = balance amount ; 22 i f (empty( cv ) ) wait = f a l s e ; 23 else signal ( cv ) ; 24 } 25 } 9

10 Note that after a deposit executes signal(fw) it might happen that other deposits are executed before the awakened withdrawal. However, new withdrawals are delayed (since wait is true), which means that the awakened withdrawal can safely decrease the balance whenever it gains execution control. Also, after executing signal(cv) at the end of withdraw, a deposit may get execution control before the awakened withdrawal is. However, again it is the case that new withdrawals are delayed on cv since wait is true. Exercise 6 (Monitor solution to the Readers/writers problem) This monitor is used to control reader- and writer access to a shared resource. ([?, fig. 5.5, page 216]) Listing 7: Readers/writers 1 monitor RW Controller { # RW ( nr = 0 or nw = 0) and nw 1 2 int nr :=0, nw:=0 3 cond oktoread ; # s i g n a l l e d when nw = 0 4 cond o k t o w r i t e ; # s i g ed when nr = 0 and nw = procedure r e q u e s t r e a d ( ) { 7 while (nw > 0) wait ( oktoread ) ; 8 nr := nr + 1 ; 9 } 10 procedure r e l e a s e r e a d ( ) { 11 nr := nr 1 ; 12 i f nr = 0 signal ( o k t o w r i t e ) ; 13 } procedure r e q u e s t w r i t e ( ) { 16 while ( nr > 0 or nw > 0) wait ( o k t o w rite ) ; 17 nw := nw + 1 ; 18 } procedure r e l e a s e w r i t e ( ) { 21 nw := nw 1; 22 signal ( o k t o w r i t e ) ; # wake up 1 w r i t e r 23 s i g n a l a l l ( oktoread ) ; # wake up a l l r e aders 24 } 25 } You may assume that signaling is handled by the signal and continue discipline. 1. In the monitor the primitive signal all is used. Modify the monitor so that it uses signal. 2. In the given monitor readers take precedence over writers. Modify the monitor such that writers take precedence over readers. Someone comes up with the following modified versions of request read and release write to solve this problem: 1 procedure r e q u e s t r e a d ( ) { 2 while (nw > 0! empty( o k t o w rite ) ) wait ( oktoread ) ; 3 nr := nr + 1 ; 4 } 5 6 procedure r e l e a s e w r i t e ( ) { 7 nw := nw 1 ; 8 i f (! empty( o k t o w r i t e ) signal ( o k t o w rite ) ; 9 else s i g n a l a l l ( oktoread ) ; 10

11 10 } Even though it may seem like a straightforward solution, it does not guarantee preference to writers. (Try to imagine why before continue reading.) Consider the situation where exactly one writer process is delayed on oktowrite when another writer starts execution of release write. After signal(oktowrite), the waiting writer is moved back into the entry queue of the monitor. Now, empty(oktowrite) is true and nw = 0. Thus, a newly arriving reader is given access to the shared resource. Thus,!empty(oktowrite) is not a sufficient condition to guarantee absence of waiting writers. In this and the remaining parts of the exercise, we will therefore follow the outline from [?, exercise 5.7] (here in this sheet, it s Exercise 4) and use counters to count the number of delayed processes. 3. Modify the monitor so that readers and writers is allowed to access the resource in turns, if both readers and writers want to access the resource. 4. Modify the monitor such that both readers and writers access the resource in a first-comefirst-served (FCFS) manner. Allow more than one reader to access the resource as long as the FCFS-principle is satisfied. Assume given a (FIFO) queue q with the following operations; enqueue(q,x) returns q with the element X added at the end of the queue. The operation dequeue(q) returns q with the first element removed and inspect(q) returns the first element of the queue without altering q. This queue will be used to order the processes. The operation empty(q) returns true only when q is empty, and an empty queue is declared by the statement queue q := empty Solution: [of Exercise 6] 1. We modify the release write procedure. The solution is straightforward, if we we can test the queue for emptyness. 1 procedure r e l e a s e w r i t e ( ) { 2 nw := nw 1 ; 3 signal ( o k t o w r i t e ) ; 4 while (! empty( oktoread ) ) signal ( oktoread ) ; 5 } 2. The standard solution gives preferences to readers in a certain manner. It s not built it into the code, but by the nature of the synchronization problem in that a reading process allows further readers to enter, but prohibits writers. The precedence to writers we are supposed to do here is of a different nature. A solution giving preference to writers. A reader must wait if a writer is active of course and as before or if there are any delayed writers! We extend the code with a counter that counts the number of delayed writers and modify request read and release write and request write. It is not necessary to count the number of delayed readers. 1 monitor RW Controller { Listing 8: R/W, writers precedence 2 int nr = 0, nw = 0 ; ## ( nr = 0 OR nw = 0) AND nw 1 11

12 3 int dw = 0 ; 4 cond oktoread ; # s i g n a l e d when nw = 0 5 cond o k t o w r i t e ; # s i g n a l e d when nr = 0 and nw = procedure r e q u e s t r e a d ( ) { # reading has l e s s p r i o r i t y 8 while (nw + dw > 0) wait ( oktoread ) ; 9 nr := nr + 1 ; 10 } 11 procedure r e l e a s e r e a d ( ) { # unchanged 12 nr := nr 1 ; 13 i f ( nr = 0) signal ( o k t o w rite ) ; # awaken one w r i t e r 14 } 15 procedure r e q u e s t w r i t e ( ) { 16 while ( nr > 0 nw > 0) { # b a s i c i n v a r i a n t unchanged 17 dw := dw + 1 ; # i n d i c a t e your W wish 18 wait ( o k t o w r i t e ) ; 19 dw := dw 1 ; # W wish has been granted 20 } 21 nw := nw + 1 ; 22 } 23 procedure r e l e a s e w r i t e ( ) { 24 nw := nw 1 ; 25 i f (! empty( o k t o w r i t e ) ) signal ( o k t o w rite ) ; # awake 1 w r i t e r and 26 else s i g n a l a l l ( oktoread ) ; # a l l readers 27 } 28 } In order to serve writers in a FCFS manner, we only need to change the code of request write: 1 procedure r e q u e s t w r i t e ( ) { 2 i f ( nr + nw + dw > 0) { 3 dw = dw + 1 ; 4 wait ( o k t o w r i t e ) ; 5 dw = dw 1 ; 6 } 7 nw = nw + 1 ; 8 } 3. When a reader releases the critical region, the critical region must be handed over to a waiting writer (if any). When a writer leaves the critical region, access must be given to a waiting reader. The solution below awakens all waiting readers when a writer finishes. With Signal and Continue, the signaled processes are moved over to the entry queue where they compete with other processes for monitor access. We must therefore program in order to avoid that a new writer gets access to the critical section before the awakened readers. We achieve this by having two counters dr and dw counting the number of delayed readers and writers, respectively. A new reader must wait if there are active or delayed writers. A new writer must wait if there are active or delayed readers or active or delayed writers. As explained in the solution to exercise 5.7 last week, we need a separate counter ensuring that all signalled processes starts execution before any new signalling happens (by using startup below). This is only needed in association with signal all. Compare also the one-lane bridge in Exercise 4 on page 2, in particular the sub-task with fairness, see the fair solution from Listing 3 on page 5, and the discussion there. There the problem was to protect the safety invariant Listing 9: R/W with turns 12

13 1 monitor RW Controller { 2 int nr = 0, nw = 0 ; ## ( nr == 0 nw == 0) && nw <= 1 3 int dr = 0 ; dw = 0 ; # d elayed r e aders and w r i t e r s 4 int startup = 0 ; 5 cond oktoread ; # s i g n a l e d when nw == 0 6 cond o k t o w r i t e ; # s i g n a l e d when nr == 0 and nw == procedure r e q u e s t r e a d ( ) { 9 i f (nw + dw > 0) { # a c t i v e w r i t e r or d e layed p r o c e s s e s 10 dr := dr + 1 ; # now we cound the d e layed readers, too 11 wait ( oktoread ) ; 12 dr := dr 1 ; 13 startup := startup 1 ; 14 } 15 nr := nr + 1 ; 16 } 17 procedure r e l e a s e r e a d ( ) { 18 nr := nr 1 ; 19 i f ( nr = 0 && startup = 0) signal ( o k t o w rite ) ; # awaken one w r i t e r 20 } 21 procedure r e q u e s t w r i t e ( ) { 22 i f (nw + nr + dr + dw > 0) { # a c t i v e or w a i t i n g p r o c e s s e s 23 dw := dw + 1 ; 24 wait ( o k t o w rite ) ; 25 dw := dw 1 ; 26 } 27 nw := nw + 1 ; 28 } 29 procedure r e l e a s e w r i t e ( ) { 30 nw := nw 1 ; 31 i f ( dr > 0) { 32 s i g n a l a l l ( oktoread ) ; 33 startup := dr ; 34 } 35 else signal ( o k t o w r i t e ) ; 36 } 37 } 4. If we can check the queue, it s easy to enqueue all enter-request. The basic entryconditions from the original formulation from Listing 7 on page 10 are unchanged, except that here we don t use the while-loop. Besides that, we use the queue as additional condition: if the queue q is non-empty, the process has to enqueue itself. By enqueue-itself is, it enters an entry into the queue in that it marks whether it s a reader or a writer. Besides that, it enqueues it s identity in the queue associated with the condition variable. Since we have two condition variables, there are two different cv-process queues. However, there s only one handmade queue q. The operation inspect(q) will be used to control the signaling. We represent the readers with the value false and the writers with the value true on the queue. The solution uses passing the condition in the sense that q will never be empty after we have signaled a condition variable, but before the process has entered the monitor. (In contrast to queues on condition variables which becomes empty if only one process waited on the queue.) By this, we avoid that a new process can sneak past the signaled process. 1 monitor RW Controller { Listing 10: RW: FCFS 2 bool READER = f a l s e ; # t h e s e two are c o n s t a n t s 13

14 3 bool WRITER = true ; 4 int nr = 0, nw = 0 ; 5 cond oktoread ; 6 cond o k t o w r i t e ; 7 queue q = empty ; # d e c l a r a t i o n o f empty queue 8 9 procedure r e q u e s t r e a d ( ) { 10 i f (nw > 0 q!= empty) { # a c t i v e w r i t e r or w a i t i n g p r o c e s s 11 q = enqueue(q,reader) ; # update the queue with w a i t i n g reader 12 wait ( oktoread ) ; 13 q = dequeue(q ) ; # remove the f i r s t element on the queue 14 } 15 nr = nr + 1 ; 16 i f (q!= empty && 17 inspect (q)=reader) # s t i l l reader f i r s t on the queue ; 18 signal ( oktoread ) ; # awaken i t 19 } 20 procedure r e l e a s e r e a d ( ) { # At t h i s point, we may s i g n a l a 21 nr = nr 1 ; # w r i t e r i f i t i s in f r o n t o f the 22 i f ( nr == 0 && inspect (q ) ) # queue. 23 signal ( o k t o w r i t e ) ; 24 } procedure r e q u e s t w r i t e ( ) { 27 i f ( nr > 0 nw > 0 q!= empty) { # a c t i v e or w a i t i n g p r o c e s s e s 28 q = enqueue(q,writer) ; # update the queue with 29 wait ( o k t o w r i t e ) ; # w a i t i n g w r i t e r. 30 q = dequeue(q ) ; # remove f i r s t. 31 } 32 nw = nw + 1 ; 33 } 34 procedure r e l e a s e w r i t e ( ) { 35 nw = nw 1 ; 36 i f (q!= empty) { # some p r o c e s s i s w a i t i n g 37 i f ( inspect (q)=reader) # the next one i s a READER 38 signal ( oktoread ) ; 39 else # the next one i s a WRITER 40 signal ( o k t o w r i t e ) ; 41 } 42 } 43 } Exercise 7 (Additional exercise: Cigarette smokers) As an extra challenge, you may try to solve the Cigarette Smokers Problem, Exercise 4.27 in Andrews. This is a surprisingly hard problem. You might take the following discussion as a starting point. First we model the agent. 1 # I n i t i a l l y, t he agent i s ready to put i n g r e d i e n t s on the t a b l e 2 # This semaphore i s used to make the agent wait f o r a smoker to f i n i s h 3 4 sem go := 1 ; 5 6 # These are one i f t he corresponding i n g r e d i e n c e i s on the t a b l e 7 sem tobacco := 0, paper := 0, match := 0 ; 8 9 process Agent { 10 co 14

15 11 while ( true ) { 12 P( go ) ; V( tobacco ) ; V( paper ) ; 13 } while ( true ) { 16 P( go ) ; V( tobacco ) ; V( match ) ; 17 } while ( true ) { 20 P( go ) ; V( paper ) ; V( match ) ; 21 } 22 co 23 } A first attempt to model the smokers might be something like this (the process called Match is the one needing matches and so on). 1 process Match { process Tobacco process Paper 2 while ( true ) { while ( true ) { while ( true ) { 3 P( tobacco ) ; P( paper ) ; P( tobacco ) ; 4 P( paper ) ; P( match ) ; P( match ) ; 5 # make c i g a r e t t e # make c i g a r e t t e # make c i g a r e t t e 6 V( go ) ; V( go ) ; V( go ) ; 7 } } } 8 } } } However, this solution has a deadlock problems. For instance, if tobacco and paper is on the table, the process Match should make a cigarette. However the Paper process may pick up the tobacco before Match, leading to a deadlock. Notice that the agent is only allowed to communicate with the smokers through the four given semaphores. It is therefore no solution to add three other semaphores used to announce which ingredient the agent did not put on the table. Solution: We split the above three processes in two parts. One for synchronization and one for smoking. We let each process pick a particular item from the table. In this solution, we let Match pick the match and so on (but we could have chosen another ordering). After picking up, the processes put the items in a cup, modelled by the semaphore array s. This cup is passed around the table. If a process has picked up an ingredient from the table, it is placed in the cup. If tobacco and match is placed in the cup, the final value of t below will be 3. We program in a way such that the Paper process delays on s[3]. When the last item is put in the cup, we signal the corresponding process which empties the cup. We make no changes to the agent given above. We need the following additional global variables 1 sem s [ 3 : 6 ] = {0,0,0,0} # m o d e l l i n g the p o s s i b l e combination 2 # o f cup items. s [ 4 ] i s not used 3 4 int t = 0 ; 5 sem mutex = 1 ; # used f o r mutex to the cup The Match process is responsible for picking up the match when there is one on the table and place it in the cup. 1 process Match { 2 co 3 while ( true ) { 4 P( match ) ; # p i c k a match when t h e r e i s one on the t a b l e 15

16 5 P( mutex ) ; 6 t = t + 1 ; # p l a c e match in cup. 1 i s the match number 7 i f ( t!= 1) V( s [ t ] ) ; # s i g n a l when the cup i s f u l l 8 V( mutex ) ; 9 } while ( true ) { 12 P( s [ 6 ] ) ; # tobacco and paper in the cup 13 t = 0 ; # empty cup 14 # make c i g a r e t t e 15 V( go ) # s i g n a l agent 16 } 17 oc 18 } The other processes follow the same pattern. 1 process Tobacco { process Paper { 2 co co 3 while ( true ) { while ( true ) { 4 P( tobacco ) ; P( paper ) ; 5 P( mutex ) ; P( mutex ) ; 6 t = t + 2 ; t = t + 4 ; 7 i f ( t!= 2) V( s [ t ] ) ; i f ( t!= 4) V( s [ t ] ) ; 8 V( mutex ) ; V( mutex ) ; 9 } } while ( true ) { while ( true ) { 12 P( s [ 5 ] ) ; P( s [ 3 ] ) ; 13 t = 0 ; t = 0 ; 14 # make c i g a r e t t e # make c i g a r e t t e 15 V( go ) ; V( go ) ; 16 } } 17 oc oc 18 } } 16

INF 4140: Models of Concurrency Series 3

INF 4140: Models of Concurrency Series 3 Universitetet i Oslo Institutt for Informatikk PMA Olaf Owe, Martin Steffen, Toktam Ramezani INF 4140: Models of Concurrency Høst 2016 Series 3 14. 9. 2016 Topic: Semaphores (Exercises with hints for solution)

More information

INF Models of concurrency

INF Models of concurrency Monitors INF4140 - Models of concurrency Monitors, lecture 4 Fall 2017 27. September 2017 2 / 49 Overview Concurrent execution of different processes Communication by shared variables Processes may interfere

More information

Improper Nesting Example

Improper Nesting Example Improper Nesting Example One of the limits on the use of parbegin/parend, and any related constructs, is that the program involved must be properly nested. Not all programs are. For example, consider the

More information

Correctness of Concurrent Programs

Correctness of Concurrent Programs Correctness of Concurrent Programs Trifon Ruskov ruskov@tu-varna.acad.bg Technical University of Varna - Bulgaria Correctness of Concurrent Programs Correctness of concurrent programs needs to be formalized:

More information

Lecture 4: Process Management

Lecture 4: Process Management Lecture 4: Process Management Process Revisited 1. What do we know so far about Linux on X-86? X-86 architecture supports both segmentation and paging. 48-bit logical address goes through the segmentation

More information

INF Models of concurrency

INF Models of concurrency INF4140 - Models of concurrency Fall 2017 October 17, 2017 Abstract This is the handout version of the slides for the lecture (i.e., it s a rendering of the content of the slides in a way that does not

More information

Clojure Concurrency Constructs, Part Two. CSCI 5828: Foundations of Software Engineering Lecture 13 10/07/2014

Clojure Concurrency Constructs, Part Two. CSCI 5828: Foundations of Software Engineering Lecture 13 10/07/2014 Clojure Concurrency Constructs, Part Two CSCI 5828: Foundations of Software Engineering Lecture 13 10/07/2014 1 Goals Cover the material presented in Chapter 4, of our concurrency textbook In particular,

More information

Solution to Proof Questions from September 1st

Solution to Proof Questions from September 1st Solution to Proof Questions from September 1st Olena Bormashenko September 4, 2011 What is a proof? A proof is an airtight logical argument that proves a certain statement in general. In a sense, it s

More information

TDDB68 Concurrent programming and operating systems. Lecture: CPU Scheduling II

TDDB68 Concurrent programming and operating systems. Lecture: CPU Scheduling II TDDB68 Concurrent programming and operating systems Lecture: CPU Scheduling II Mikael Asplund, Senior Lecturer Real-time Systems Laboratory Department of Computer and Information Science Copyright Notice:

More information

Distributed Systems Part II Solution to Exercise Sheet 10

Distributed Systems Part II Solution to Exercise Sheet 10 Distributed Computing HS 2012 Prof. R. Wattenhofer / C. Decker Distributed Systems Part II Solution to Exercise Sheet 10 1 Spin Locks A read-write lock is a lock that allows either multiple processes to

More information

Unary negation: T F F T

Unary negation: T F F T Unary negation: ϕ 1 ϕ 1 T F F T Binary (inclusive) or: ϕ 1 ϕ 2 (ϕ 1 ϕ 2 ) T T T T F T F T T F F F Binary (exclusive) or: ϕ 1 ϕ 2 (ϕ 1 ϕ 2 ) T T F T F T F T T F F F Classical (material) conditional: ϕ 1

More information

Proof Techniques (Review of Math 271)

Proof Techniques (Review of Math 271) Chapter 2 Proof Techniques (Review of Math 271) 2.1 Overview This chapter reviews proof techniques that were probably introduced in Math 271 and that may also have been used in a different way in Phil

More information

Safety and Liveness. Thread Synchronization: Too Much Milk. Critical Sections. A Really Cool Theorem

Safety and Liveness. Thread Synchronization: Too Much Milk. Critical Sections. A Really Cool Theorem Safety and Liveness Properties defined over an execution of a program Thread Synchronization: Too Much Milk Safety: nothing bad happens holds in every finite execution prefix Windows never crashes No patient

More information

CS 453 Operating Systems. Lecture 7 : Deadlock

CS 453 Operating Systems. Lecture 7 : Deadlock CS 453 Operating Systems Lecture 7 : Deadlock 1 What is Deadlock? Every New Yorker knows what a gridlock alert is - it s one of those days when there is so much traffic that nobody can move. Everything

More information

INF Models of concurrency

INF Models of concurrency INF4140 - Models of concurrency RPC and Rendezvous INF4140 Lecture 15. Nov. 2017 RPC and Rendezvous Outline More on asynchronous message passing interacting processes with different patterns of communication

More information

Math 38: Graph Theory Spring 2004 Dartmouth College. On Writing Proofs. 1 Introduction. 2 Finding A Solution

Math 38: Graph Theory Spring 2004 Dartmouth College. On Writing Proofs. 1 Introduction. 2 Finding A Solution Math 38: Graph Theory Spring 2004 Dartmouth College 1 Introduction On Writing Proofs What constitutes a well-written proof? A simple but rather vague answer is that a well-written proof is both clear and

More information

A Brief Introduction to Proofs

A Brief Introduction to Proofs A Brief Introduction to Proofs William J. Turner October, 010 1 Introduction Proofs are perhaps the very heart of mathematics. Unlike the other sciences, mathematics adds a final step to the familiar scientific

More information

Calculus II. Calculus II tends to be a very difficult course for many students. There are many reasons for this.

Calculus II. Calculus II tends to be a very difficult course for many students. There are many reasons for this. Preface Here are my online notes for my Calculus II course that I teach here at Lamar University. Despite the fact that these are my class notes they should be accessible to anyone wanting to learn Calculus

More information

Computer Science 324 Computer Architecture Mount Holyoke College Fall Topic Notes: Digital Logic

Computer Science 324 Computer Architecture Mount Holyoke College Fall Topic Notes: Digital Logic Computer Science 324 Computer Architecture Mount Holyoke College Fall 2007 Topic Notes: Digital Logic Our goal for the next few weeks is to paint a a reasonably complete picture of how we can go from transistor

More information

Chapter 2. Mathematical Reasoning. 2.1 Mathematical Models

Chapter 2. Mathematical Reasoning. 2.1 Mathematical Models Contents Mathematical Reasoning 3.1 Mathematical Models........................... 3. Mathematical Proof............................ 4..1 Structure of Proofs........................ 4.. Direct Method..........................

More information

Unit: Blocking Synchronization Clocks, v0.3 Vijay Saraswat

Unit: Blocking Synchronization Clocks, v0.3 Vijay Saraswat Unit: Blocking Synchronization Clocks, v0.3 Vijay Saraswat This lecture discusses X10 clocks. For reference material please look at the chapter on Clocks in []. 1 Motivation The central idea underlying

More information

Checking Consistency. Chapter Introduction Support of a Consistent Family

Checking Consistency. Chapter Introduction Support of a Consistent Family Chapter 11 Checking Consistency 11.1 Introduction The conditions which define a consistent family of histories were stated in Ch. 10. The sample space must consist of a collection of mutually orthogonal

More information

Scheduling I. Today Introduction to scheduling Classical algorithms. Next Time Advanced topics on scheduling

Scheduling I. Today Introduction to scheduling Classical algorithms. Next Time Advanced topics on scheduling Scheduling I Today Introduction to scheduling Classical algorithms Next Time Advanced topics on scheduling Scheduling out there You are the manager of a supermarket (ok, things don t always turn out the

More information

Mathematical Foundations of Programming. Nicolai Kraus. Draft of February 15, 2018

Mathematical Foundations of Programming. Nicolai Kraus. Draft of February 15, 2018 Very short lecture notes: Mathematical Foundations of Programming University of Nottingham, Computer Science, module code G54FOP, Spring 2018 Nicolai Kraus Draft of February 15, 2018 What is this? This

More information

Program Analysis Part I : Sequential Programs

Program Analysis Part I : Sequential Programs Program Analysis Part I : Sequential Programs IN5170/IN9170 Models of concurrency Program Analysis, lecture 5 Fall 2018 26. 9. 2018 2 / 44 Program correctness Is my program correct? Central question for

More information

process arrival time CPU burst time priority p1 0ms 25ms 3 p2 1ms 9ms 1 p3 20ms 14ms 4 p4 32ms 4ms 2

process arrival time CPU burst time priority p1 0ms 25ms 3 p2 1ms 9ms 1 p3 20ms 14ms 4 p4 32ms 4ms 2 Homework #2 Solutions 1. Suppose that the following processes arrive for execution at the times indicated. Each process will run with a single burst of CPU activity (i.e., no I/O) which lasts for the listed

More information

Math 300: Foundations of Higher Mathematics Northwestern University, Lecture Notes

Math 300: Foundations of Higher Mathematics Northwestern University, Lecture Notes Math 300: Foundations of Higher Mathematics Northwestern University, Lecture Notes Written by Santiago Cañez These are notes which provide a basic summary of each lecture for Math 300, Foundations of Higher

More information

1 Boolean Algebra Simplification

1 Boolean Algebra Simplification cs281: Computer Organization Lab3 Prelab Our objective in this prelab is to lay the groundwork for simplifying boolean expressions in order to minimize the complexity of the resultant digital logic circuit.

More information

Exercises Solutions. Automation IEA, LTH. Chapter 2 Manufacturing and process systems. Chapter 5 Discrete manufacturing problems

Exercises Solutions. Automation IEA, LTH. Chapter 2 Manufacturing and process systems. Chapter 5 Discrete manufacturing problems Exercises Solutions Note, that we have not formulated the answers for all the review questions. You will find the answers for many questions by reading and reflecting about the text in the book. Chapter

More information

5 ProbabilisticAnalysisandRandomized Algorithms

5 ProbabilisticAnalysisandRandomized Algorithms 5 ProbabilisticAnalysisandRandomized Algorithms This chapter introduces probabilistic analysis and randomized algorithms. If you are unfamiliar with the basics of probability theory, you should read Appendix

More information

CS162 Operating Systems and Systems Programming Lecture 7 Semaphores, Conditional Variables, Deadlocks"

CS162 Operating Systems and Systems Programming Lecture 7 Semaphores, Conditional Variables, Deadlocks CS162 Operating Systems and Systems Programming Lecture 7 Semaphores, Conditional Variables, Deadlocks" September 19, 2012! Ion Stoica! http://inst.eecs.berkeley.edu/~cs162! Recap: Monitors" Monitors represent

More information

Lab Course: distributed data analytics

Lab Course: distributed data analytics Lab Course: distributed data analytics 01. Threading and Parallelism Nghia Duong-Trung, Mohsan Jameel Information Systems and Machine Learning Lab (ISMLL) University of Hildesheim, Germany International

More information

An introduction to Uppaal and Timed Automata MVP5 1

An introduction to Uppaal and Timed Automata MVP5 1 An introduction to Uppaal and Timed Automata MVP5 1 What is Uppaal? (http://www.uppaal.com/) A simple graphical interface for drawing extended finite state machines (automatons + shared variables A graphical

More information

Writing proofs for MATH 61CM, 61DM Week 1: basic logic, proof by contradiction, proof by induction

Writing proofs for MATH 61CM, 61DM Week 1: basic logic, proof by contradiction, proof by induction Writing proofs for MATH 61CM, 61DM Week 1: basic logic, proof by contradiction, proof by induction written by Sarah Peluse, revised by Evangelie Zachos and Lisa Sauermann September 27, 2016 1 Introduction

More information

Dartmouth Computer Science Technical Report TR Efficient Wait-Free Implementation of Multiword LL/SC Variables

Dartmouth Computer Science Technical Report TR Efficient Wait-Free Implementation of Multiword LL/SC Variables Dartmouth Computer Science Technical Report TR2004-523 Efficient Wait-Free Implementation of Multiword LL/SC Variables Prasad Jayanti and Srdjan Petrovic Department of Computer Science Dartmouth College

More information

Writing Mathematical Proofs

Writing Mathematical Proofs Writing Mathematical Proofs Dr. Steffi Zegowitz The main resources for this course are the two following books: Mathematical Proofs by Chartrand, Polimeni, and Zhang How to Think Like a Mathematician by

More information

MATH 521, WEEK 2: Rational and Real Numbers, Ordered Sets, Countable Sets

MATH 521, WEEK 2: Rational and Real Numbers, Ordered Sets, Countable Sets MATH 521, WEEK 2: Rational and Real Numbers, Ordered Sets, Countable Sets 1 Rational and Real Numbers Recall that a number is rational if it can be written in the form a/b where a, b Z and b 0, and a number

More information

Reading 5 : Induction

Reading 5 : Induction CS/Math 40: Introduction to Discrete Mathematics Fall 015 Instructors: Beck Hasti and Gautam Prakriya Reading 5 : Induction In the last reading we began discussing proofs. We mentioned some proof paradigms

More information

Introduction to Model Checking. Debdeep Mukhopadhyay IIT Madras

Introduction to Model Checking. Debdeep Mukhopadhyay IIT Madras Introduction to Model Checking Debdeep Mukhopadhyay IIT Madras How good can you fight bugs? Comprising of three parts Formal Verification techniques consist of three parts: 1. A framework for modeling

More information

Hardy s Paradox. Chapter Introduction

Hardy s Paradox. Chapter Introduction Chapter 25 Hardy s Paradox 25.1 Introduction Hardy s paradox resembles the Bohm version of the Einstein-Podolsky-Rosen paradox, discussed in Chs. 23 and 24, in that it involves two correlated particles,

More information

Sequential programs. Uri Abraham. March 9, 2014

Sequential programs. Uri Abraham. March 9, 2014 Sequential programs Uri Abraham March 9, 2014 Abstract In this lecture we deal with executions by a single processor, and explain some basic notions which are important for concurrent systems as well.

More information

Scheduling I. Today. Next Time. ! Introduction to scheduling! Classical algorithms. ! Advanced topics on scheduling

Scheduling I. Today. Next Time. ! Introduction to scheduling! Classical algorithms. ! Advanced topics on scheduling Scheduling I Today! Introduction to scheduling! Classical algorithms Next Time! Advanced topics on scheduling Scheduling out there! You are the manager of a supermarket (ok, things don t always turn out

More information

CMSC 451: Lecture 7 Greedy Algorithms for Scheduling Tuesday, Sep 19, 2017

CMSC 451: Lecture 7 Greedy Algorithms for Scheduling Tuesday, Sep 19, 2017 CMSC CMSC : Lecture Greedy Algorithms for Scheduling Tuesday, Sep 9, 0 Reading: Sects.. and. of KT. (Not covered in DPV.) Interval Scheduling: We continue our discussion of greedy algorithms with a number

More information

Agreement. Today. l Coordination and agreement in group communication. l Consensus

Agreement. Today. l Coordination and agreement in group communication. l Consensus Agreement Today l Coordination and agreement in group communication l Consensus Events and process states " A distributed system a collection P of N singlethreaded processes w/o shared memory Each process

More information

1 Lamport s Bakery Algorithm

1 Lamport s Bakery Algorithm Com S 6 Spring Semester 2009 Algorithms for Multiprocessor Synchronization Lecture 3: Tuesday, 27th January 2009 Instructor: Soma Chaudhuri Scribe: Neeraj Khanolkar Lamport s Bakery Algorithm Algorithm

More information

Central Algorithmic Techniques. Iterative Algorithms

Central Algorithmic Techniques. Iterative Algorithms Central Algorithmic Techniques Iterative Algorithms Code Representation of an Algorithm class InsertionSortAlgorithm extends SortAlgorithm { void sort(int a[]) throws Exception { for (int i = 1; i < a.length;

More information

Writing proofs for MATH 51H Section 2: Set theory, proofs of existential statements, proofs of uniqueness statements, proof by cases

Writing proofs for MATH 51H Section 2: Set theory, proofs of existential statements, proofs of uniqueness statements, proof by cases Writing proofs for MATH 51H Section 2: Set theory, proofs of existential statements, proofs of uniqueness statements, proof by cases September 22, 2018 Recall from last week that the purpose of a proof

More information

Operating Systems. VII. Synchronization

Operating Systems. VII. Synchronization Operating Systems VII. Synchronization Ludovic Apvrille ludovic.apvrille@telecom-paristech.fr Eurecom, office 470 http://soc.eurecom.fr/os/ @OS Eurecom Outline Synchronization issues 2/22 Fall 2017 Institut

More information

Lecture Notes on Proofs & Arithmetic

Lecture Notes on Proofs & Arithmetic 15-424: Foundations of Cyber-Physical Systems Lecture Notes on Proofs & Arithmetic André Platzer Carnegie Mellon University Lecture 9 1 Introduction Lecture 8 on Events & Delays discussed and developed

More information

Math 138: Introduction to solving systems of equations with matrices. The Concept of Balance for Systems of Equations

Math 138: Introduction to solving systems of equations with matrices. The Concept of Balance for Systems of Equations Math 138: Introduction to solving systems of equations with matrices. Pedagogy focus: Concept of equation balance, integer arithmetic, quadratic equations. The Concept of Balance for Systems of Equations

More information

PHYSICS 212 LABORATORY MANUAL CALVIN COLLEGE

PHYSICS 212 LABORATORY MANUAL CALVIN COLLEGE PHYSICS 212 LABORATORY MANUAL CALVIN COLLEGE 2003 Physics 212 Calvin College Variables and Fair Tests (adapted from Physics 113 lab manual) Suppose I wanted to determine whether being in darkness would

More information

An Intuitive Introduction to Motivic Homotopy Theory Vladimir Voevodsky

An Intuitive Introduction to Motivic Homotopy Theory Vladimir Voevodsky What follows is Vladimir Voevodsky s snapshot of his Fields Medal work on motivic homotopy, plus a little philosophy and from my point of view the main fun of doing mathematics Voevodsky (2002). Voevodsky

More information

Basic counting techniques. Periklis A. Papakonstantinou Rutgers Business School

Basic counting techniques. Periklis A. Papakonstantinou Rutgers Business School Basic counting techniques Periklis A. Papakonstantinou Rutgers Business School i LECTURE NOTES IN Elementary counting methods Periklis A. Papakonstantinou MSIS, Rutgers Business School ALL RIGHTS RESERVED

More information

HOW TO CREATE A PROOF. Writing proofs is typically not a straightforward, algorithmic process such as calculating

HOW TO CREATE A PROOF. Writing proofs is typically not a straightforward, algorithmic process such as calculating HOW TO CREATE A PROOF ALLAN YASHINSKI Abstract We discuss how to structure a proof based on the statement being proved Writing proofs is typically not a straightforward, algorithmic process such as calculating

More information

Information-Theoretic Lower Bounds on the Storage Cost of Shared Memory Emulation

Information-Theoretic Lower Bounds on the Storage Cost of Shared Memory Emulation Information-Theoretic Lower Bounds on the Storage Cost of Shared Memory Emulation Viveck R. Cadambe EE Department, Pennsylvania State University, University Park, PA, USA viveck@engr.psu.edu Nancy Lynch

More information

Essential facts about NP-completeness:

Essential facts about NP-completeness: CMPSCI611: NP Completeness Lecture 17 Essential facts about NP-completeness: Any NP-complete problem can be solved by a simple, but exponentially slow algorithm. We don t have polynomial-time solutions

More information

Module 03 Lecture 14 Inferential Statistics ANOVA and TOI

Module 03 Lecture 14 Inferential Statistics ANOVA and TOI Introduction of Data Analytics Prof. Nandan Sudarsanam and Prof. B Ravindran Department of Management Studies and Department of Computer Science and Engineering Indian Institute of Technology, Madras Module

More information

Reading and Writing. Mathematical Proofs. Slides by Arthur van Goetham

Reading and Writing. Mathematical Proofs. Slides by Arthur van Goetham Reading and Writing Mathematical Proofs Slides by Arthur van Goetham What is a proof? Why explanations are not proofs What is a proof? A method for establishing truth What establishes truth depends on

More information

Proving Programs Correct

Proving Programs Correct Proving Programs Correct Page 1 of 9 Proving Programs Correct How can we be sure that a piece of code does what we want it to do? One way is to try testing the code on a large group of data. Another is

More information

Recitation 4: Eventful Tactical KeYmaera X Proofs /15-624/ Logical Foundations of Cyber-Physical Systems

Recitation 4: Eventful Tactical KeYmaera X Proofs /15-624/ Logical Foundations of Cyber-Physical Systems Recitation 4: Eventful Tactical KeYmaera X Proofs 15-424/15-624/15-824 Logical Foundations of Cyber-Physical Systems 1 Announcements Notes by: Brandon Bohrer Edits by: Yong Kiam Tan (yongkiat@cs.cmu.edu)

More information

Math 308 Midterm Answers and Comments July 18, Part A. Short answer questions

Math 308 Midterm Answers and Comments July 18, Part A. Short answer questions Math 308 Midterm Answers and Comments July 18, 2011 Part A. Short answer questions (1) Compute the determinant of the matrix a 3 3 1 1 2. 1 a 3 The determinant is 2a 2 12. Comments: Everyone seemed to

More information

Lab Exercise 03: Gauss Law

Lab Exercise 03: Gauss Law PHYS 2212 Lab Exercise 03: Gauss Law PRELIMINARY MATERIAL TO BE READ BEFORE LAB PERIOD Counting Field Lines: Electric Flux Recall that an electric field (or, for that matter, magnetic field) can be difficult

More information

Let s now begin to formalize our analysis of sequential machines Powerful methods for designing machines for System control Pattern recognition Etc.

Let s now begin to formalize our analysis of sequential machines Powerful methods for designing machines for System control Pattern recognition Etc. Finite State Machines Introduction Let s now begin to formalize our analysis of sequential machines Powerful methods for designing machines for System control Pattern recognition Etc. Such devices form

More information

CSE613: Parallel Programming, Spring 2012 Date: May 11. Final Exam. ( 11:15 AM 1:45 PM : 150 Minutes )

CSE613: Parallel Programming, Spring 2012 Date: May 11. Final Exam. ( 11:15 AM 1:45 PM : 150 Minutes ) CSE613: Parallel Programming, Spring 2012 Date: May 11 Final Exam ( 11:15 AM 1:45 PM : 150 Minutes ) This exam will account for either 10% or 20% of your overall grade depending on your relative performance

More information

INF Models of concurrency

INF Models of concurrency INF4140 - Models of concurrency Høsten 2015 November 18, 2015 Abstract This is the handout version of the slides for the lecture (i.e., it s a rendering of the content of the slides in a way that does

More information

CPU scheduling. CPU Scheduling

CPU scheduling. CPU Scheduling EECS 3221 Operating System Fundamentals No.4 CPU scheduling Prof. Hui Jiang Dept of Electrical Engineering and Computer Science, York University CPU Scheduling CPU scheduling is the basis of multiprogramming

More information

TDDI04, K. Arvidsson, IDA, Linköpings universitet CPU Scheduling. Overview: CPU Scheduling. [SGG7] Chapter 5. Basic Concepts.

TDDI04, K. Arvidsson, IDA, Linköpings universitet CPU Scheduling. Overview: CPU Scheduling. [SGG7] Chapter 5. Basic Concepts. TDDI4 Concurrent Programming, Operating Systems, and Real-time Operating Systems CPU Scheduling Overview: CPU Scheduling CPU bursts and I/O bursts Scheduling Criteria Scheduling Algorithms Multiprocessor

More information

CSE 380 Computer Operating Systems

CSE 380 Computer Operating Systems CSE 380 Computer Operating Systems Instructor: Insup Lee & Dianna Xu University of Pennsylvania, Fall 2003 Lecture Note 3: CPU Scheduling 1 CPU SCHEDULING q How can OS schedule the allocation of CPU cycles

More information

CS 374: Algorithms & Models of Computation, Spring 2017 Greedy Algorithms Lecture 19 April 4, 2017 Chandra Chekuri (UIUC) CS374 1 Spring / 1

CS 374: Algorithms & Models of Computation, Spring 2017 Greedy Algorithms Lecture 19 April 4, 2017 Chandra Chekuri (UIUC) CS374 1 Spring / 1 CS 374: Algorithms & Models of Computation, Spring 2017 Greedy Algorithms Lecture 19 April 4, 2017 Chandra Chekuri (UIUC) CS374 1 Spring 2017 1 / 1 Part I Greedy Algorithms: Tools and Techniques Chandra

More information

Graph Theory. Thomas Bloom. February 6, 2015

Graph Theory. Thomas Bloom. February 6, 2015 Graph Theory Thomas Bloom February 6, 2015 1 Lecture 1 Introduction A graph (for the purposes of these lectures) is a finite set of vertices, some of which are connected by a single edge. Most importantly,

More information

Simulation of Process Scheduling Algorithms

Simulation of Process Scheduling Algorithms Simulation of Process Scheduling Algorithms Project Report Instructor: Dr. Raimund Ege Submitted by: Sonal Sood Pramod Barthwal Index 1. Introduction 2. Proposal 3. Background 3.1 What is a Process 4.

More information

Elementary Linear Algebra, Second Edition, by Spence, Insel, and Friedberg. ISBN Pearson Education, Inc., Upper Saddle River, NJ.

Elementary Linear Algebra, Second Edition, by Spence, Insel, and Friedberg. ISBN Pearson Education, Inc., Upper Saddle River, NJ. 2008 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. APPENDIX: Mathematical Proof There are many mathematical statements whose truth is not obvious. For example, the French mathematician

More information

Lock using Bakery Algorithm

Lock using Bakery Algorithm Lock using Bakery Algorithm Shankar April 16, 2014 Overview Classical mutual exclusion problem given program with critical sections and threads 0..N 1 obtain entry and exit code for each critical section

More information

6.080 / Great Ideas in Theoretical Computer Science Spring 2008

6.080 / Great Ideas in Theoretical Computer Science Spring 2008 MIT OpenCourseWare http://ocw.mit.edu 6.080 / 6.089 Great Ideas in Theoretical Computer Science Spring 2008 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.

More information

CSE 331 Winter 2018 Reasoning About Code I

CSE 331 Winter 2018 Reasoning About Code I CSE 331 Winter 2018 Reasoning About Code I Notes by Krysta Yousoufian Original lectures by Hal Perkins Additional contributions from Michael Ernst, David Notkin, and Dan Grossman These notes cover most

More information

We are going to discuss what it means for a sequence to converge in three stages: First, we define what it means for a sequence to converge to zero

We are going to discuss what it means for a sequence to converge in three stages: First, we define what it means for a sequence to converge to zero Chapter Limits of Sequences Calculus Student: lim s n = 0 means the s n are getting closer and closer to zero but never gets there. Instructor: ARGHHHHH! Exercise. Think of a better response for the instructor.

More information

COS433/Math 473: Cryptography. Mark Zhandry Princeton University Spring 2017

COS433/Math 473: Cryptography. Mark Zhandry Princeton University Spring 2017 COS433/Math 473: Cryptography Mark Zhandry Princeton University Spring 2017 Previously on COS 433 Takeaway: Crypto is Hard Designing crypto is hard, even experts get it wrong Just because I don t know

More information

Distributed Systems Principles and Paradigms

Distributed Systems Principles and Paradigms Distributed Systems Principles and Paradigms Chapter 6 (version April 7, 28) Maarten van Steen Vrije Universiteit Amsterdam, Faculty of Science Dept. Mathematics and Computer Science Room R4.2. Tel: (2)

More information

1.1 Statements and Compound Statements

1.1 Statements and Compound Statements Chapter 1 Propositional Logic 1.1 Statements and Compound Statements A statement or proposition is an assertion which is either true or false, though you may not know which. That is, a statement is something

More information

A Short Introduction to Hoare Logic

A Short Introduction to Hoare Logic A Short Introduction to Hoare Logic Supratik Chakraborty I.I.T. Bombay June 23, 2008 Supratik Chakraborty (I.I.T. Bombay) A Short Introduction to Hoare Logic June 23, 2008 1 / 34 Motivation Assertion checking

More information

Doc112: Hardware. Department of Computing, Imperial College London. Doc112: Hardware Lecture 1 Slide 1

Doc112: Hardware. Department of Computing, Imperial College London. Doc112: Hardware Lecture 1 Slide 1 Doc112: Hardware Department of Computing, Imperial College London Doc112: Hardware Lecture 1 Slide 1 First Year Computer Hardware Course Lecturers Duncan Gillies Bjoern Schuller Doc112: Hardware Lecture

More information

Tutorial on Mathematical Induction

Tutorial on Mathematical Induction Tutorial on Mathematical Induction Roy Overbeek VU University Amsterdam Department of Computer Science r.overbeek@student.vu.nl April 22, 2014 1 Dominoes: from case-by-case to induction Suppose that you

More information

Arithmetic: Decimals, Fractions and Percentages

Arithmetic: Decimals, Fractions and Percentages A B UNIT Lesson Plan Fractions and Place value and conversion of decimals to fractions T: Can you remember the place value table? Can you tell me the headings we use? Ps:... hundreds, tens, units, tenths,

More information

ALGEBRA. 1. Some elementary number theory 1.1. Primes and divisibility. We denote the collection of integers

ALGEBRA. 1. Some elementary number theory 1.1. Primes and divisibility. We denote the collection of integers ALGEBRA CHRISTIAN REMLING 1. Some elementary number theory 1.1. Primes and divisibility. We denote the collection of integers by Z = {..., 2, 1, 0, 1,...}. Given a, b Z, we write a b if b = ac for some

More information

Che-Wei Chang Department of Computer Science and Information Engineering, Chang Gung University

Che-Wei Chang Department of Computer Science and Information Engineering, Chang Gung University Che-Wei Chang chewei@mail.cgu.edu.tw Department of Computer Science and Information Engineering, Chang Gung University } 2017/11/15 Midterm } 2017/11/22 Final Project Announcement 2 1. Introduction 2.

More information

CSC501 Operating Systems Principles. Deadlock

CSC501 Operating Systems Principles. Deadlock CSC501 Operating Systems Principles Deadlock 1 Last Lecture q Priority Inversion Q Priority Inheritance Protocol q Today Q Deadlock 2 The Deadlock Problem q Definition Q A set of blocked processes each

More information

Quadratic Equations Part I

Quadratic Equations Part I Quadratic Equations Part I Before proceeding with this section we should note that the topic of solving quadratic equations will be covered in two sections. This is done for the benefit of those viewing

More information

After that, we will introduce more ideas from Chapter 5: Number Theory. Your quiz in recitation tomorrow will involve writing proofs like those.

After that, we will introduce more ideas from Chapter 5: Number Theory. Your quiz in recitation tomorrow will involve writing proofs like those. Wednesday, Oct 17 Today we will finish Course Notes 3.2: Methods of Proof. After that, we will introduce more ideas from Chapter 5: Number Theory. The exercise generator Methods of Proof, 3.2 (also includes

More information

PEANO AXIOMS FOR THE NATURAL NUMBERS AND PROOFS BY INDUCTION. The Peano axioms

PEANO AXIOMS FOR THE NATURAL NUMBERS AND PROOFS BY INDUCTION. The Peano axioms PEANO AXIOMS FOR THE NATURAL NUMBERS AND PROOFS BY INDUCTION The Peano axioms The following are the axioms for the natural numbers N. You might think of N as the set of integers {0, 1, 2,...}, but it turns

More information

This is logically equivalent to the conjunction of the positive assertion Minimal Arithmetic and Representability

This is logically equivalent to the conjunction of the positive assertion Minimal Arithmetic and Representability 16.2. MINIMAL ARITHMETIC AND REPRESENTABILITY 207 If T is a consistent theory in the language of arithmetic, we say a set S is defined in T by D(x) if for all n, if n is in S, then D(n) is a theorem of

More information

Mathematics for Computer Science Exercises from Chapter 3

Mathematics for Computer Science Exercises from Chapter 3 Mathematics for Computer Science Exercises from Chapter 3 Silvio Capobianco Last update: 19 September 2018 Problems from Section 3.1 Problem 3.2. Your class has a textbook and a final exam. Let P, Q, and

More information

CPU Scheduling Exercises

CPU Scheduling Exercises CPU Scheduling Exercises NOTE: All time in these exercises are in msec. Processes P 1, P 2, P 3 arrive at the same time, but enter the job queue in the order presented in the table. Time quantum = 3 msec

More information

Exercises Stochastic Performance Modelling. Hamilton Institute, Summer 2010

Exercises Stochastic Performance Modelling. Hamilton Institute, Summer 2010 Exercises Stochastic Performance Modelling Hamilton Institute, Summer Instruction Exercise Let X be a non-negative random variable with E[X ]

More information

Theoretical Cryptography, Lecture 10

Theoretical Cryptography, Lecture 10 Theoretical Cryptography, Lecture 0 Instructor: Manuel Blum Scribe: Ryan Williams Feb 20, 2006 Introduction Today we will look at: The String Equality problem, revisited What does a random permutation

More information

Deadlock. CSE 2431: Introduction to Operating Systems Reading: Chap. 7, [OSC]

Deadlock. CSE 2431: Introduction to Operating Systems Reading: Chap. 7, [OSC] Deadlock CSE 2431: Introduction to Operating Systems Reading: Chap. 7, [OSC] 1 Outline Resources Deadlock Deadlock Prevention Deadlock Avoidance Deadlock Detection Deadlock Recovery 2 Review: Synchronization

More information

Module 5: CPU Scheduling

Module 5: CPU Scheduling Module 5: CPU Scheduling Basic Concepts Scheduling Criteria Scheduling Algorithms Multiple-Processor Scheduling Real-Time Scheduling Algorithm Evaluation 5.1 Basic Concepts Maximum CPU utilization obtained

More information

Lecture Notes on Inductive Definitions

Lecture Notes on Inductive Definitions Lecture Notes on Inductive Definitions 15-312: Foundations of Programming Languages Frank Pfenning Lecture 2 September 2, 2004 These supplementary notes review the notion of an inductive definition and

More information

The Underlying Semantics of Transition Systems

The Underlying Semantics of Transition Systems The Underlying Semantics of Transition Systems J. M. Crawford D. M. Goldschlag Technical Report 17 December 1987 Computational Logic Inc. 1717 W. 6th St. Suite 290 Austin, Texas 78703 (512) 322-9951 1

More information

EE 144/244: Fundamental Algorithms for System Modeling, Analysis, and Optimization Fall 2016

EE 144/244: Fundamental Algorithms for System Modeling, Analysis, and Optimization Fall 2016 EE 144/244: Fundamental Algorithms for System Modeling, Analysis, and Optimization Fall 2016 Discrete Event Simulation Stavros Tripakis University of California, Berkeley Stavros Tripakis (UC Berkeley)

More information

Probability (Devore Chapter Two)

Probability (Devore Chapter Two) Probability (Devore Chapter Two) 1016-345-01: Probability and Statistics for Engineers Fall 2012 Contents 0 Administrata 2 0.1 Outline....................................... 3 1 Axiomatic Probability 3

More information