CP Safety and Synchronization CP Concurrent Programming 3

  • Slides: 30
Download presentation
CP — Safety and Synchronization CP — Concurrent Programming 3. Safety and Synchronization Prof.

CP — Safety and Synchronization CP — Concurrent Programming 3. Safety and Synchronization Prof. O. Nierstrasz Wintersemester 2005 / 2006 © Oscar Nierstrasz

CP — Safety and Synchronization Overview > Modelling interaction in FSP > Safety —

CP — Safety and Synchronization Overview > Modelling interaction in FSP > Safety — synchronizing critical sections — Locking for atomicity — The busy-wait mutual exclusion protocol > Conditional synchronization — Slots in FSP — wait(), notify() and notify. All() — Slots in Java Selected material © Magee and Kramer © Oscar Nierstrasz 2

CP — Safety and Synchronization Modelling interaction — shared actions Actions that are common

CP — Safety and Synchronization Modelling interaction — shared actions Actions that are common between two processes are shared and can be used to model process interaction: > Unshared actions may be arbitrarily interleaved > Shared actions occur simultaneously for all participants MAKER = ( make -> ready -> MAKER ). USER = ( ready -> use -> USER ). ||MAKER_USER = ( MAKER || USER ). What are the states of the LTS? The traces? © Oscar Nierstrasz 0 1 3

CP — Safety and Synchronization Modelling interaction — handshake A handshake is an action

CP — Safety and Synchronization Modelling interaction — handshake A handshake is an action that signals acknowledgement MAKERv 2 = ( make -> ready -> used -> MAKERv 2 ). USERv 2 = ( ready -> used -> USERv 2 ). ||MAKER_USERv 2 = ( MAKERv 2 || USERv 2 ). What are the states and traces of the LTS? 0 © Oscar Nierstrasz 1 4

CP — Safety and Synchronization Safety problems Objects must only be accessed when they

CP — Safety and Synchronization Safety problems Objects must only be accessed when they are in a consistent state, formalized by a class invariant. Each method assumes the class invariant holds when it starts, and it re-establishes it when done. m 1 Consistent states m 2 m 3 ? ! m 4 m 5 If methods interleave arbitrarily, an inconsistent state may be accessed, and the object may be left in a “dirty” state. © Oscar Nierstrasz Where shared resources are updated may be a critical section. 5

CP — Safety and Synchronization Atomicity and interference Consider the two processes: AInc: BInc:

CP — Safety and Synchronization Atomicity and interference Consider the two processes: AInc: BInc: © Oscar Nierstrasz {x=0} x : = x+1 {x=? } How can these processes interfere? 6

CP — Safety and Synchronization Atomic actions Individual reads and writes may be atomic

CP — Safety and Synchronization Atomic actions Individual reads and writes may be atomic actions: const N range T = 3 = 0. . N Var[u: T] = Var[0], = ( read[u] | write[v: T] -> Var[u] -> Var[v] ). set Var. Alpha = { read[T], write[T] } Inc = ( read[v: 0. . N-1] -> write[v+1] -> STOP ) © Oscar Nierstrasz +Var. Alpha. 7

CP — Safety and Synchronization Sequential behaviour A single sequential thread requires no synchronization:

CP — Safety and Synchronization Sequential behaviour A single sequential thread requires no synchronization: ||Seq. Inc = (Var||Inc). 0 © Oscar Nierstrasz 1 8

CP — Safety and Synchronization Inc read[0] write[0] 00 read[0] 01 read[1] read[0] /

CP — Safety and Synchronization Inc read[0] write[0] 00 read[0] 01 read[1] read[0] / write[0] write[1] 02 read[2] 03 04 13 14 23 24 33 34 read[0] write[1] Var write[1] write[0] 10 11 write[2] 20 21 22 write[3] 31 32 write[3] 30 © Oscar Nierstrasz read[1] write[1] 12 write[2] 9

CP — Safety and Synchronization Concurrent behaviour Without synchronization, concurrent threads may interfere: ||Par.

CP — Safety and Synchronization Concurrent behaviour Without synchronization, concurrent threads may interfere: ||Par. Inc = ({a, b}: : Var || a: Inc || b: Inc). 0 © Oscar Nierstrasz 1 10

CP — Safety and Synchronization Locking Locks are used to make a critical section

CP — Safety and Synchronization Locking Locks are used to make a critical section atomic: LOCK = INC = ( ( -> -> acquire -> release -> LOCK ). acquire read[v: 0. . N-1] write[v+1] release STOP ) +Var. Alpha. 0 © Oscar Nierstrasz 1 11

CP — Safety and Synchronization Processes can synchronize critical sections by sharing a lock:

CP — Safety and Synchronization Processes can synchronize critical sections by sharing a lock: ||Par. Inc 2 = ({a, b}: : VAR || {a, b}: : LOCK || a: INC || b: INC). 0 © Oscar Nierstrasz 1 12

CP — Safety and Synchronization in Java Threads also synchronize using locks: synchronized T

CP — Safety and Synchronization in Java Threads also synchronize using locks: synchronized T m() { // method body } is just convenient syntax for: T m() { synchronized (this) { // method body } } Every object has a lock, and Threads may use them to synchronize with each other. © Oscar Nierstrasz 13

CP — Safety and Synchronization Busy-Wait Mutual Exclusion Protocol P 1 sets enter 1

CP — Safety and Synchronization Busy-Wait Mutual Exclusion Protocol P 1 sets enter 1 : = true when it wants to enter its CS, but sets turn : = “P 2” to yield priority to P 2 process P 1 loop enter 1 : = true turn : = “P 2” while enter 2 and turn = “P 2” do skip Critical Section enter 1 : = false Non-critical Section end process P 2 loop enter 2 : = true turn : = “P 1” while enter 1 and turn = “P 1” do skip Critical Section enter 2 : = false Non-critical Section end Is this protocol correct? Is it fair? Deadlock-free? © Oscar Nierstrasz 14

CP — Safety and Synchronization Atomic read and write range T = 1. .

CP — Safety and Synchronization Atomic read and write range T = 1. . 2 We can model integer and boolean variables as processes with atomic read and write actions: Var = Var[1], Var[u: T] = ( read[u] | write[v: T] -> Var[u] -> Var[v]). set Bool = {true, false} BOOL(Init='false) = BOOL[Init], BOOL[b: Bool] = ( is[b] -> BOOL[b] | set. To[x: Bool] -> BOOL[x]). © Oscar Nierstrasz 15

CP — Safety and Synchronization Modelling the busy-wait protocol Each process performs two actions

CP — Safety and Synchronization Modelling the busy-wait protocol Each process performs two actions in its CS: P 1 = ( enter 1. set. To['true] -> turn. write[2] -> Gd 1), Gd 1 = ( enter 2. is['false] -> CS 1 | enter 2. is['true] -> ( turn. read[1] -> CS 1 | turn. read[2] -> Gd 1)), CS 1 = ( a -> b -> enter 1. set. To['false] -> P 1). P 2 = ( enter 2. set. To['true] -> turn. write[1] -> Gd 2), Gd 2 = ( enter 1. is['false] -> CS 2 | enter 1. is['true] -> ( turn. read[2] -> CS 2 | turn. read[1] -> Gd 2)), CS 2 = ( c -> d -> enter 2. set. To['false] -> P 2). ||Busy. Wait = (enter 1: BOOL||enter 2: BOOL||turn: Var||P 1||P 2)@{a, b, c, d}. © Oscar Nierstrasz 16

CP — Safety and Synchronization Busy-wait composition Very pretty, but how do we know

CP — Safety and Synchronization Busy-wait composition Very pretty, but how do we know there are no errors? ! 0 © Oscar Nierstrasz 1 17

CP — Safety and Synchronization Checking for errors We can check for errors by

CP — Safety and Synchronization Checking for errors We can check for errors by composing our system with an agent that moves to the ERROR state if atomicity is violated: Ok = ( a -> ( c -> ERROR | b -> Ok ) | c -> ( a -> ERROR | d -> Ok)). ||Busy. Wait. OK = (enter 1: BOOL||enter 2: BOOL||turn: Var||P 1||P 2||Ok). What happens if we break the protocol? © Oscar Nierstrasz 0 1 18

CP — Safety and Synchronization Conditional synchronization A lock delays an acquire request if

CP — Safety and Synchronization Conditional synchronization A lock delays an acquire request if it is already locked: LOCK = ( acquire -> release -> LOCK ). Similarly, a one-slot buffer delays a put request if it is full and delays a get request if it is empty: const N = 2 Slot = ( put[v: 0. . N] -> get[v] -> Slot ). © Oscar Nierstrasz 19

CP — Safety and Synchronization Producer/Consumer composition Producer = ( put[0] -> put[1] ->

CP — Safety and Synchronization Producer/Consumer composition Producer = ( put[0] -> put[1] -> put[2] -> Producer ). Consumer = ( get[x: 0. . N] -> Consumer ). ||Chain = ( Producer || Slot || Consumer ) 0 © Oscar Nierstrasz 1 20

CP — Safety and Synchronization Wait and notify A Java object whose methods are

CP — Safety and Synchronization Wait and notify A Java object whose methods are all synchronized behaves like a monitor Within a synchronized method or block: > wait() suspends the current thread, releasing the lock > notify() wakes up one thread waiting on that object > notify. All() wakes up all threads waiting on that object Outside of a synchronized block, wait() and notify() will raise an Illegal. Monitor. State. Exception Always use notify. All() unless you are sure it doesn’t matter which thread you wake up! © Oscar Nierstrasz 21

CP — Safety and Synchronization Slot (put) class Slot implements Buffer { private Object

CP — Safety and Synchronization Slot (put) class Slot implements Buffer { private Object slot. Val; // initially null public synchronized void put(Object val) { while (slot. Val != null) { try { wait(); } // become Not. Runnable catch (Interrupted. Exception e) { } } slot. Val = val; notify. All(); // make waiting threads Runnable return; } … interface Buffer { public void put(Object val); public Object get(); } © Oscar Nierstrasz 22

CP — Safety and Synchronization Slot (get) … public synchronized Object get() { Object

CP — Safety and Synchronization Slot (get) … public synchronized Object get() { Object rval; while (slot. Val == null) { try { wait(); } catch (Interrupted. Exception e) { } } rval = slot. Val; slot. Val = null; notify. All(); return rval; } } © Oscar Nierstrasz 23

CP — Safety and Synchronization Active objects abstract class Active. Object extends Thread {

CP — Safety and Synchronization Active objects abstract class Active. Object extends Thread { protected int count_; Active. Object(String name, int count) { super(name); count_ = count; } public void run() { int i; for (i=1; i<=count_; i++) { this. action(i); this. random. Sleep(); } } protected abstract void action(int n); protected void random. Sleep() { … } } © Oscar Nierstrasz An active object has a thread of its own. 24

CP — Safety and Synchronization Producer in Java The Producer puts _count messages to

CP — Safety and Synchronization Producer in Java The Producer puts _count messages to the slot: class Producer extends Active. Object { protected Buffer slot_; protected String wares_; Producer(String name, int count, Buffer slot, String wares) { super(name, count); slot_ = slot; wares_ = wares; } protected void action(int n) { String message; message = wares_ + "(" + String. value. Of(n) + ")"; slot_. put(message); System. out. println(get. Name() + " put " + message); } } © Oscar Nierstrasz 25

CP — Safety and Synchronization Consumer in Java. . . and the Consumer gets

CP — Safety and Synchronization Consumer in Java. . . and the Consumer gets them: class Consumer extends Active. Object { protected Buffer slot_; Consumer(String name, int count, Buffer slot) { super(name, count); slot_ = slot; } protected void action(int n) { String message; message = (String) slot_. get(); System. out. println(get. Name() + " got " + message); } } © Oscar Nierstrasz 26

CP — Safety and Synchronization Composing Producers and Consumers Multiple producers and consumers may

CP — Safety and Synchronization Composing Producers and Consumers Multiple producers and consumers may share the buffer: public static void Producer. Consumer. Demo() { Buffer slot = new Slot(); new Producer("Peter", "apple ", slot, count). start(); new Producer("Paula", "orange", slot, count). start(); new Producer("Patricia", "banana", slot, count). start(); new Consumer("Carla", slot, count). start(); new Consumer("Cris", slot, 2*count). start(); } © Oscar Nierstrasz Peter put apple (1) Carla got apple (1) Paula put orange(1) Cris got orange(1) Patricia put banana(1) Carla got banana(1) Peter put apple (2) Cris got apple (2) Patricia put banana(2) Carla got banana(2) Peter put apple (3) Cris got apple (3) Paula put orange(2) Carla got orange(2) Patricia put banana(3) Cris got banana(3) Peter put apple (4) Cris got apple (4) Peter put apple (5) Carla got apple (5) Paula put orange(3) Cris got orange(3) Patricia put banana(4) Cris got banana(4) Patricia put banana(5) Cris got banana(5) Paula put orange(4) Cris got orange(4) Paula put orange(5) Cris got orange(5) 27

CP — Safety and Synchronization What you should know! > How do you model

CP — Safety and Synchronization What you should know! > How do you model interaction with FSP? > What is a critical section? What is critical about it? > Why don’t sequential programs need synchronization? > How do locks address safety problems? > What primitives do you need to implement the busy-wait mutex protocol? > How can you use FSP to check for safety violations? > What happens if you call wait or notify outside a synchronized method or block? > When is it safe to use notify. All()? © Oscar Nierstrasz 28

CP — Safety and Synchronization Can you answer these questions? > What is an

CP — Safety and Synchronization Can you answer these questions? > What is an example of an invariant that might be > > > violated by interfering, concurrent threads? What constitute atomic actions in Java? Can you ensure safety in concurrent programs without using locks? When should you use synchronize(this) rather than synchronize(some. Object)? Is the busy-wait mutex protocol fair? Deadlock-free? How would you implement a Lock class in Java? Why is the Java Slot class so much more complex than the FSP Slot specification? © Oscar Nierstrasz 29

CP — Safety and Synchronization License > http: //creativecommons. org/licenses/by-sa/2. 5/ Attribution-Share. Alike 2.

CP — Safety and Synchronization License > http: //creativecommons. org/licenses/by-sa/2. 5/ Attribution-Share. Alike 2. 5 You are free: • to copy, distribute, display, and perform the work • to make derivative works • to make commercial use of the work Under the following conditions: Attribution. You must attribute the work in the manner specified by the author or licensor. Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a license identical to this one. • For any reuse or distribution, you must make clear to others the license terms of this work. • Any of these conditions can be waived if you get permission from the copyright holder. Your fair use and other rights are in no way affected by the above. © Oscar Nierstrasz 30