lecture04

# lecture04 - CS140 Winter 2008 Handout#4 Past Present CS 140...

This preview shows pages 1–2. Sign up to view the full content.

CS140 - Winter 2008 -Handout±#4 1 CS 140: Operating Systems Lecture 4: Synchronization Mendel Rosenblum ± Shared resources often require “mutual exclusion” A mutual exclusion constraint between two events is a requirement that they not overlap in time. Conceptually: a thread is assigned exclusive use of a resource until it is done performing a critical set of operations. ± Today: Some details about threads How to simplify the construction of critical regions using semaphores and monitors Reading: (6 th ed.: Ch. 4.5, 7; 7 th ed.: Ch. 3.[5,6], 6) Some nuances of the whole lot t1 t2 t3 Spinning tricks ± Initial spin was pretty simplistic: ± Atomic instructions are costly, so want to avoid ± Problem: what happens if L put in register? lock(L) { for(acquired = 0; !acquired; ) aswap acquired, L; } lock(l) { for(acquired = 0; !acquired; ) while(!L) ; aswap acquired, L; } Locking variations ± Recursive locks Why? Synchronization modularity ± “trylocks”: non-blocking lock acquisition recursive_lock(l) { if(l->owner == cur_thread) l->count++; else lock(l->lock); l->count = 0; l->owner = cur_thread; recursive_unlock(l) { if(l->owner != cur_thread || l->count < 0) fatal(bogus release!); l->count--; if(!l->count) unlock(l->lock); l->owner = -1; if ( !try_lock( l ) ) return RESOURCE_BLOCKED; Blocking mechanics ± Producer/consumers: producer puts characters in an infinite buffer, consumers pull out ± what are some problems? char buf[]; /* infinite buf */ int head = 0, n = 0, tail = 0; lock l; void put(char c) lock(l); buf[head++] = c; n++; unlock(l); wake_sleepers(l); int get(char c) { lock(l); if(!n) unlock(l); sleep(l); lock(l); c = buf[tail++]; n--; unlock(l); return c; Semaphores ± Synchronization variable [Dijkstra, 1960s] A non-negative integer counter with atomic increment and decrement. Blocks rather than going negative. Used for mutual exclusion and scheduling ± Two operations on semaphore: P(sem): decrement counter “sem”. If sem = 0, then block until greater than zero. Also called wait()/down(). V(sem): increment counter “sem by one and wake 1 waiting

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 4

lecture04 - CS140 Winter 2008 Handout#4 Past Present CS 140...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online