Скачать презентацию CPS 110 Thread cooperation Landon Cox Constraining Скачать презентацию CPS 110 Thread cooperation Landon Cox Constraining

30ec91a41aa54076fb2fb10c6fc2fd1f.ppt

  • Количество слайдов: 44

CPS 110: Thread cooperation Landon Cox CPS 110: Thread cooperation Landon Cox

Constraining concurrency ê Synchronization ê Controlling thread interleavings ê Some events are independent ê Constraining concurrency ê Synchronization ê Controlling thread interleavings ê Some events are independent ê No shared state ê Relative order of these events don’t matter ê Other events are dependent ê Output of one can be input to another ê Their order can affect program results

Goals of synchronization 1. All interleavings must give correct result ê Correct concurrent program Goals of synchronization 1. All interleavings must give correct result ê Correct concurrent program ê Works no matter how fast threads run ê Important for your projects! 2. Constrain program as little as possible ê Constraints slow program down ê Constraints create complexity

“Too much milk” principals “Too much milk” principals

“Too much milk” rules ê The fridge must be stocked with milk ê Milk “Too much milk” rules ê The fridge must be stocked with milk ê Milk expires quickly, so never > 1 milk ê Landon and Melissa ê Can come home at any time ê If either sees an empty fridge, must buy milk ê Code (no synchronization) if (no. Milk){ buy milk; }

Unsynchronized code will break Time 3: 00 3: 05 3: 10 3: 15 3: Unsynchronized code will break Time 3: 00 3: 05 3: 10 3: 15 3: 20 3: 25 3: 30 3: 35 Look in fridge (no milk) Go to grocery store Look in fridge (no milk) Buy milk Go to grocery store Arrive home, stock fridge Buy milk Arrive home, stock fridge Too much milk!

What broke? ê Code worked sometimes, but not always ê Code contained a race What broke? ê Code worked sometimes, but not always ê Code contained a race condition ê Processor speed caused incorrect result ê First type of synchronization ê Mutual exclusion ê Critical sections

Synchronization concepts ê Mutual exclusion ê ê Ensure 1 thread doing something at a Synchronization concepts ê Mutual exclusion ê ê Ensure 1 thread doing something at a time E. g. 1 person shops at a time Code blocks are atomic w/re to each other Threads can’t run code blocks at same time

Synchronization concepts ê Critical section ê Code block that must run atomically ê “with Synchronization concepts ê Critical section ê Code block that must run atomically ê “with respect to some other pieces of code” ê If A and B are critical w/re to each other ê Threads mustn’t interleave events in A and B ê A and B mutually exclude each other ê Often conflicting code is same block ê But executed by different threads ê Reads/writes shared data (e. g. screen, fridge)

Back to “Too much milk” ê What is the critical section? if (no. Milk){ Back to “Too much milk” ê What is the critical section? if (no. Milk){ buy milk; } ê Landon and Melissa’s critical sections ê Must be atomic w/re to each other

“Too much milk” solution 1 ê Assume only atomic load/store ê Build larger atomic “Too much milk” solution 1 ê Assume only atomic load/store ê Build larger atomic section from load/store ê Idea: 1. Leave notes to say you’re taking care of it 2. Don’t check milk if there is a note

Solution 1 code ê Atomic operations ê Atomic load: check note ê Atomic store: Solution 1 code ê Atomic operations ê Atomic load: check note ê Atomic store: leave note if (no. Milk) { if (no. Note){ leave note; buy milk; remove note; } }

Does it work? if (no. Milk) { 1 if (no. Note){ 2 if (no. Does it work? if (no. Milk) { 1 if (no. Note){ 2 if (no. Note){ leave note; 3 buy milk; 4 buy milk; remove note; } } Is this better than no synchronization at all? What if “if” sections are switched?

What broke? ê Melissa’s events can happen ê After Landon checks for a note What broke? ê Melissa’s events can happen ê After Landon checks for a note ê Before Landon leaves a note if (no. Milk) { if (no. Note){ leave note; buy milk; remove note; } }

Next solution ê Idea: ê Change the order of “leave note”, “check note” ê Next solution ê Idea: ê Change the order of “leave note”, “check note” ê Requires labeled notes (else you’ll see your note)

Does it work? leave note. Landon if (no note. Melissa){ if (no. Milk){ buy Does it work? leave note. Landon if (no note. Melissa){ if (no. Milk){ buy milk; } } remove note. Landon leave note. Melissa if (no note. Landon){ if (no. Milk){ buy milk; } } remove note. Melissa Nope. (Illustration of “starvation. ”)

What about now? while (no. Milk){ leave note. Landon if(no note. Melissa){ if(no. Milk){ What about now? while (no. Milk){ leave note. Landon if(no note. Melissa){ if(no. Milk){ buy milk; } } remove note. Landon } while (no. Milk){ leave note. Melissa if(no note. Landon){ if(no. Milk){ buy milk; } } remove note. Melissa } Nope. (Same starvation problem as before)

Next solution ê We’re getting closer ê Problem ê Who buys milk if both Next solution ê We’re getting closer ê Problem ê Who buys milk if both leave notes? ê Solution ê Let Landon hang around to make sure job is done

Does it work? leave note. Landon while (note. Melissa){ do nothing } if (no. Does it work? leave note. Landon while (note. Melissa){ do nothing } if (no. Milk){ buy milk; } remove note. Landon leave note. Melissa if (no note. Landon){ if (no. Milk){ buy milk; } } remove note. Melissa Yes! It does work! Can you show it?

Downside of solution ê Complexity ê Hard to convince yourself it works ê Asymmetric Downside of solution ê Complexity ê Hard to convince yourself it works ê Asymmetric ê Landon and Melissa run different code ê Not clear if this scales to > 2 people ê Landon consumes CPU while waiting ê Busy-waiting ê Note: only needed atomic load/store

Raising the level of abstraction ê Mutual exclusion with atomic load/store ê Painful to Raising the level of abstraction ê Mutual exclusion with atomic load/store ê Painful to program ê Wastes resources ê Need more HW support ê Will be covered later ê OS can provide higher level abstractions

Course administration ê Project 0 ê Due soon ê Do not use you late Course administration ê Project 0 ê Due soon ê Do not use you late days on P 0 ê (only worth 2% of your grade) ê Save your late days for bigger projects ê Some groups have submitted ê Questions about Project 0?

Course administration void main () { // create a new list Dlist<foo> *list = Course administration void main () { // create a new list Dlist *list = new Dlist (); // insert a new object list->insert. Front (new foo ()); How much memory should be allocated // remove and delete the object here? delete list->remove. Front (); // insert another object How much memory list->insert. Front (new foo ()); should be allocated // delete the list here? delete list; }

Course administration ê Project 1 (two parts) 1. 2. Write a small concurrent program Course administration ê Project 1 (two parts) 1. 2. Write a small concurrent program Implement a thread library (single CPU) ê Create new threads ê Switch between threads ê Manage interactions btw cooperating threads ê Out on Wednesday, should be able to start ê E. g. disk scheduler input routine

Course administration ê Groups ê Everyone should have a group ê Everyone should have Course administration ê Groups ê Everyone should have a group ê Everyone should have a CS account ê Discussion section ê Friday ê Office hours ê Tuesday, Friday ê Any other questions?

Too much milk solution leave note. Landon while (note. Melissa){ do nothing } if Too much milk solution leave note. Landon while (note. Melissa){ do nothing } if (no. Milk){ buy milk; } remove note. Landon leave note. Melissa if (no note. Landon){ if (no. Milk){ buy milk; } } remove note. Melissa

Downside of solution ê Complexity ê Hard to convince yourself it works ê Asymmetric Downside of solution ê Complexity ê Hard to convince yourself it works ê Asymmetric ê Landon and Melissa run different code ê Not clear if this scales to > 2 people ê Landon consumes CPU while waiting ê Busy-waiting ê Note: only needed atomic load/store

Raising the level of abstraction ê Locks ê Also called mutexes ê Provide mutual Raising the level of abstraction ê Locks ê Also called mutexes ê Provide mutual exclusion ê Prevent threads from entering a critical section ê Lock operations ê Lock (aka Lock: : acquire) ê Unlock (aka Lock: : release)

Lock operations ê Lock: wait until lock is free, then acquire it do { Lock operations ê Lock: wait until lock is free, then acquire it do { if (lock is free) { acquire lock break } } while (1) ê This is a busy-waiting implementation ê We’ll improve on this in a few lectures ê Unlock: atomic release lock Must be atomic with respect to other threads calling this code

Too much milk, solution 2 if (no. Milk) { if (no. Note){ leave note; Too much milk, solution 2 if (no. Milk) { if (no. Note){ leave note; buy milk; remove note; } } Block is not atomic. Must atomically • check if lock is free • grab it Why doesn’t the note work as a lock?

Elements of locking 1. 2. 3. 4. The lock is initially free Threads acquire Elements of locking 1. 2. 3. 4. The lock is initially free Threads acquire lock before an action Threads release lock when action completes Lock() must wait if someone else has lock ê Key idea ê All synchronization involves waiting ê Threads are either running or blocked

Too much milk with locks? lock () if (no. Milk) { buy milk } Too much milk with locks? lock () if (no. Milk) { buy milk } unlock () ê Problem? ê Waiting for lock while other buys milk

Too much milk “w/o waiting”? lock () if (no. Note && no. Milk){ leave Too much milk “w/o waiting”? lock () if (no. Note && no. Milk){ leave note “at store” Not holding unlock () buy milk lock () remove note } unlock () if (no. Note && no. Milk){ leave note “at store” unlock () buy milk lock () remove note } unlock () Only hold lock while handling shared resource.

What about this? 1 3 lock () if (no. Milk && no. Note){ leave What about this? 1 3 lock () if (no. Milk && no. Note){ leave note “at store” unlock () buy milk stock fridge remove note } else { unlock () } 2 4 lock () if (no. Milk && no. Note){ leave note “at store” unlock () buy milk stock fridge remove note } else { unlock () }

Example: thread-safe queue enqueue () { lock (q. Lock) // ptr is private // Example: thread-safe queue enqueue () { lock (q. Lock) // ptr is private // head is shared node *ptr; // find queue tail for (ptr=head; ptr->next!=0; ptr=ptr->next){} … ptr->next=new_element; new_element->next=0; unlock(q. Lock); } dequeue () { lock (q. Lock); element=head; // if queue non-empty if (head!=0) { // remove head=head->next; element->next=0; } unlock (q. Lock); return element; } What can go wrong?

Thread-safe queue ê Can enqueue unlock anywhere? ê No ê Must leave shared data Thread-safe queue ê Can enqueue unlock anywhere? ê No ê Must leave shared data ê In a consistent/sane state ê Data invariant enqueue () { lock (q. Lock) node *ptr; for (ptr=head; ptr->next!=NULL; ptr=ptr->next){} ê “consistent/sane state” ê “always” true ptr->next=new_element; unlock(q. Lock); // safe? new_element->next=0; }

Invariants ê What are the queue invariants? ê Each node appears once (from head Invariants ê What are the queue invariants? ê Each node appears once (from head to null) ê Enqueue results in prior list + new element ê Dequeue removes exactly one element ê Can invariants ever be false? ê Must be ê Otherwise you could never change states

More on invariants ê So when is the invariant broken? ê Can only be More on invariants ê So when is the invariant broken? ê Can only be broken while lock is held ê And only by thread holding the lock ê Really a “public” invariant ê What is the data’s state in when the lock is free ê Like having a room tidy before guests arrive ê Hold a lock whenever manipulating shared data

More on invariants ê What about reading shared data? ê Still must hold lock More on invariants ê What about reading shared data? ê Still must hold lock ê Else another thread could break invariant ê (Thread A prints Q as Thread B enqueues)

How about this? I’m always holding a lock while accessing shared state. ptr may How about this? I’m always holding a lock while accessing shared state. ptr may not point to tail after lock/unlock. enqueue () { lock (q. Lock) node *ptr; for (ptr=head; ptr->next!=NULL; ptr=ptr->next){} unlock (q. Lock); ptr->next=new_element; new_element->next=0; unlock(q. Lock); } Lesson: • Thinking about individual accesses is not enough • Must reason about dependencies between accesses

What about Java? Too much milk synchronized (obj){ if (no. Milk) { buy milk What about Java? Too much milk synchronized (obj){ if (no. Milk) { buy milk } } ê Every object is a lock ê Use synchronized key word ê Lock : “{“, unlock: “}”

Synchronizing methods public class Cubby. Hole { private int contents; public int get() { Synchronizing methods public class Cubby. Hole { private int contents; public int get() { return contents; } public synchronized void put(int value) { contents = value; } } ê What does this mean? What is the lock? ê “this” is the lock

Synchronizing methods public class Cubby. Hole { private int contents; public int get() { Synchronizing methods public class Cubby. Hole { private int contents; public int get() { return contents; } public void put(int value) { synchronized (this) { contents = value; } } } ê Equivalent to “synchronized (this)” block

Next class ê Mutual exclusion is great and all, but ê It not really Next class ê Mutual exclusion is great and all, but ê It not really expressive enough ê Ordering constraints ê Often must wait for something to happen ê Use something called “monitors” and/or “condition variables”