Last t ime Need f or synchronizat ion primit ives 7: Synchronizat - - PDF document

last t ime
SMART_READER_LITE
LIVE PREVIEW

Last t ime Need f or synchronizat ion primit ives 7: Synchronizat - - PDF document

Last t ime Need f or synchronizat ion primit ives 7: Synchronizat ion Locks and building locks f rom HW primit ives Semaphores and building semaphores f rom Last Modif ied: locks 6/ 7/ 2004 1:21:28 PM -1 -2 Semaphores f or


slide-1
SLIDE 1

1

  • 1

7: Synchronizat ion

Last Modif ied: 6/ 7/ 2004 1:21:28 PM

  • 2

Last t ime

Need f or synchronizat ion primit ives Locks and building locks f rom HW

primit ives

Semaphores and building semaphores f rom

locks

  • 3

Uses of Semaphores

Mut ual exclusion

Binar y semaphor es (wait / signal used j ust like

lock/ unlock)

“hold”

Managing N copies of a r esour ce

Count ing semaphor es “ent er”

Anyt hing else?

Anot her t ype of synchr onizat ion is t o expr ess

  • r der ing/ scheduling const r aint s

“Don’t allow x t o pr oceed unt il af t er y”

  • 4

Semaphores f or expressing ordering

I nit ialize semaphore value t o 0 Code:

P

i

P

j

Μ Μ A wait signal B

Execut e B in P

j only af t er A execut ed in P i

Not e: I f signal execut es f irst , wait will

f ind it is an signaled st at e (hist ory!)

  • 5

Event s and Signals

Recall: UNI X signals

Kill = send signal; Signal = cat ch signal Many syst em def ined but also signals lef t t o user

def init ion

Can be used f or synchronizat ion

  • Signal handler set s a f lag
  • Main t hr ead polls on t he value of t he f lag
  • Busy wait t hough

Window’s Event s

Synchronizat ion obj ect s used somewhat like semaphores

when t hey are used f or ordering/ scheduling const raint s

One process/ t hread can wait f or an event t o be signaled

by anot her process/ t hread

  • 6

Window’s Event s

Cr eat e/ dest r oy

HANDLE CreateEvent( LPSECURITY_ATTRIBUTES lpsa, // security privileges (default = NULL) BOOL bManualReset , // TRUE if event must be reset manually BOOL bInitialState , // TRUE to create event in signaled state LPTSTR lpszEventName ); // name of event (may be NULL) BOOL CloseHandle( hObject );

W ait

DWORD WaitForSingleObject( HANDLE hObject, // object to wait for DWORD dwMilliseconds );

Signal (all t hr eads t hat wait on it r eceive)

BOOL SetEvent ( HANDLE hEvent ); //signal on BOOL ResetEvent( HANDLE hEvent ); //signal off

slide-2
SLIDE 2

2

  • 7

Generalize t o Messaging

Synchronizat ion based on dat a t ransf er

(at omic) across a channel

I n general, messages can be used t o

express ordering/ scheduling const raint s

Wait f or message bef or e do X Send message = signal

Direct ext ension t o dist ribut ed syst ems

  • 8

Compiler help?

There is no synt act ic connect ion bet ween

t he semaphore ( or lock or event ) and t he shared dat a/ resources it is prot ect ing

Thus t he “meaning” of t he semaphore is

def ined by t he pr ogr ammer ’s use of it

Bad sof t war e engineer ing

  • Semaphores basically global variables accessed by all

t hreads

Easy f or pr ogr ammer s t o make mist akes

  • 9

P rogramming Language Support

Add programming language support f or

synchronizat ion

Declar e a sect ion of code t o r equir e mut ually

exclusive access (like J ava’s synchr onized)

Associat e t he shar ed dat a it self wit h t he

locking aut omat ically Monit or = programming language support t o

enf orce synchronizat ion

Mut ual exclusion code added by t he compiler !

  • 10

Monit ors

A monit or is a sof t ware module t hat

encapsulat es:

Shar ed dat a st r uct ur es Pr ocedur es t hat oper at ed on t hem Synchr onizat ion r equir ed of pr ocesses t hat

invoke t hese pr ocedur es Like a public/ privat e dat a int erf ace

prevent s access t o privat e dat a members; Monit ors prevent unsynchronized access t o shared dat a st ruct ures

  • 11

Example: bankAccount

Monitor bankAccount{ int balance; int readBalance( ){return balance}; void upateBalance(int newBalance){ balance = newBalance; } int withdraw ( int amount) { balance = balance – amount; return balance; } int deposit (int amount){ balance = balance + amount; return balance; } }

Locking added by t he compiler!

  • 12

Monit or

S balance r eadBalance updat eBalance wit hdraw deposit Shared dat a Pr ocedur es Wait ing queue One t hr ead I n Monit or

slide-3
SLIDE 3

3

  • 13

Wait ing I nside a Monit ors

What if you need t o wait f or an event wit hin one

  • f t he procedures of a monit or?

Monit or s as we have seen t o t his point enf or ce

mut ual exclusion – what about t he

I nt r oduce anot her synchr onizat ion obj ect , t he

condit ion var iable

Wit hin t he monit or declar e a condit ion var iable:

condit ion x;

  • 14

Wait and signal

Condit ion variables, like semaphores, have

t he t wo operat ions have t he t wo

  • perat ions, wait and signal.

The oper at ion x. wait() means t hat t he pr ocess

invoking t his oper at ion is suspended unt il anot her pr ocess invokes x. signal();

The oper at ion wait allows anot her pr ocess t o

ent er t he monit or (or no one could ever call signal!)

The x. signal oper at ion r esumes exact ly one

suspended pr ocess. I f no pr ocess is suspended, t hen t he signal oper at ion has no ef f ect

  • 15

Monit or Wit h Condit ion Variables

S balance r eadBalance updat eBalance wit hdraw deposit Wait ing queue One t hr ead Running in Monit or Condit ion Var iables and t heir associat ed wait queues

  • 16

Semaphores vs Condit ion Variables

I ’d like t o be able t o say t hat condit ion

variables are j ust like semaphores but …

Wit h condit ion variables, if no process is

suspended t hen t he signal operat ion has no ef f ect

Wit h semaphores, signal increment s t he

value regardless of whet her any process is wait ing

Semaphores have “hist ory” (t hey

remember signals) while condit ion variables have no hist ory

  • 17

Condit ion Variable Alone?

Could you use a condit ion variable concept

  • ut side of monit ors?

Yes, basically a semaphore wit hout hist ory

Couldn’t do locking wit h it because no mut ual

exclusion on it s own

Couldn’t do r esour ce management (count ing

semaphor e) because no value/ hist or y

Could you use it f or or der ing/ scheduling

const r aint s? Yes but wit h dif f er ent semant ics

  • 18

Condit ion Variables f or

  • rdering/ scheduling

Code:

P

i

P

j

Μ Μ A wait signal B

Execut e B in P

j only af t er A execut ed in P i

I f signal f ir st , it is lost ; wait will block

unt il next signal ( no hist ory!)

slide-4
SLIDE 4

4

  • 19

P seudo-Monit ors

Monit or = a lock (implied/ added by

compiler) f or mut ual exclusion PLUS zero

  • r more condit ion variables t o express
  • rdering const raint s

What if we want ed t o have monit or wit hout

programming language support ?

Declar e locks and t hen associat e condit ion

var iables wit h a lock

I f wait on t he condit ion var iable, t hen r elease

t he lock

  • 20

P t hread’s Condit ion Variables

Cr eat e/ dest r oy

int pthread _cond _init (pthread_cond_t *cond, pthread _condattr_t *attr); int pthread _cond _destroy ( pthread _cond _t *cond);

W ait

int pthread _cond _wait (pthread_cond_t *cond, pthread _mutex_t *mut );

Timed Wait

int pthread _cond _timedwait ( pthread _cond _t *cond, pthread_mutex_t *mut, const struct timespec *abstime);

Signal

int pthread _cond _signal (pthread _cond_t *cond);

Br oadcast

int pthread _cond _broadcast (pthread _cond_t *cond);

  • 21

Example: P seudo- monit ors

pthread_mutex _t monitorLock; pthread_cond_t conditionVar; void pseudoMonitorProc(void) { pthread_mutex _lock(&mutexLock ); ….. pthread_cond_wait(&conditionVar, &monitorLock); …. pthread_mutex _unlock(&mutexLock); }

  • 22

Monit or I nvariant s

Monit or invariant s = rules t hat must hold

whenever no t hread is in t he monit or

Not checked by compiler More like pre/ post condit ions t o be

respect ed by t he programmer

  • 23

Who f irst ?

I f t hread in Monit or calls x.signal waking

anot her t hread t hen who is running in t he monit or now? (Can’t bot h be running in t he monit or!)

Hoare monit ors

Signalee r uns; signaler blocks Signaler put on monit or queue

Mesa monit ors

Signaler cont inues; signalee blocks Signalee moved f r om condit ion var iable queue

t o monit or queue

  • 24

Does it mat t er? Yes

I f signalee runs immediat ely, t hen clearly

“condit ion” being signaled st ill holds

Signaler must r est or e any “monit or invar iant s”

bef or e signaling I f signalee runs lat er, t hen when it f inally

does ent er t he monit or it must recheck condit ion bef ore execut ing

Signaler need not r est or e any “monit or

invar iant s” bef or e signaling – j ust bef ore exit ing

slide-5
SLIDE 5

5

  • 25

Writ e dif f erent code as a result

I f wait er runs immediat ely t hen if (condition not true)

C.wait()

I f wait er runs lat er t hen while (condition not true)

C.wait()

Conclusion?

Mesa st yle (wait er r uns lat er ) has f ewer

cont ext swit ches and dir ect ly suppor t s a br oadcast pr imit ive (I .e. c.signalAll )

While inst ead of if not a big pr ice t o pay

  • 26

Semaphores vs Monit ors

I f have one you can implement t he ot her …

  • 27

I mplement ing Semaphores Wit h Monit ors

Monitor semaphore { int value; conditionVariable _t waitQueue ; void setValue (int value){ value = newValue; } int getValue(){return value;} void wait(){ value --; while (value < 0){ //Notice Mesa semantics condWait( &waitQueue); } } void signal (){ value++; condSignal(&waitQueue); } } //end monitor semaphore

  • 28

I mplement ing Monit ors wit h Semaphores

semaphore_t mutex , next; int nextCount = 1; Initialization code: mutex .value = 1; next.value = 0; For each procedure P in Monitor, implement P as Wait ( mutex); unsynchronizedBodyOfP (); if (nextCount >0){ signal(next); }else { signal(mutex) ; } conditionVariable_t { int count; semaphore_t sem; } condWait (conditionVariable_t *x) { //one more waiting on this cond x->count = x_count++; //wake up someone if (nextCount > 0){ signal(next); }else { signal ( mutex ); } wait(x-> sem); x->count = x- >count

  • -;

} condSignal(conditionVariable_t *x){ //if no one waiting do nothing! if (x->count > 0){ next_count = nextCount++; signal(x

  • >sem

); wait (next); nextCount --; } }

  • 29

Sof t ware Synchronizat ion P rimit ives Summary

Locks

  • Simple semant ics, of t en close t o HW primit ives
  • I f built wit hout a queue can get busy wait ing

Semaphor es

  • Value f or hist or y and queue t o avoid busy wait ing
  • Pr imit ives not as int uit ive as lock/ unlock

Event s/ Messages

  • I nt uit ive primit ives (f lag/ wait f or event , send/ wait f or

message)

  • Easily ext ended t o dist ribut ed syst ems

Monit or s

  • Language const r uct s t hat aut omat e t he locking
  • Easy t o program wit h where support ed and where model f it s

t he t ask

  • R

e-int r oduce much of t he complexit y wit h cv and monit or invariant s

  • 30

Conclusion?

Synchronizat ion primit ives all boil down t o

represent ing a large amount of shared st at e (t ime and/ or space) wit h a small amount of shared st at e (t ime and space)

All need t o be built on t op of HW support Once have one kind, can usually get t o

  • t her kinds

Which one you use is a mat t er of

programmat ic simplicit y (mat ching primit ive t o t he problem) and t ast e

slide-6
SLIDE 6

6

  • 31

Next t ime

Classic synchronizat ion problems and t heir

solut ions

Bounded Buf f er Reader s/ Wr it er s Dining Philosopher s

  • 32

Out t akes

  • 33

Adapt ive Locking in Solaris

Adapt ive mut exes

Mult iprocessor syst em if can’t get lock

  • And t hr ead wit h lock is not r unning, t hen sleep
  • And t hr ead wit h lock is r unning, spin wait

Uniprocessor if can’t get lock

  • I mmediat ely sleep (no hope f or lock t o be r eleased while

you are running)

Pr ogr ammer s choose adapt ive mut exes f or short

code segment s and semaphor es or condit ion var iables f or longer ones

Blocked t hr eads placed on separ at e queue f or

desir ed obj ect

Thread t o gain access next chosen by priorit y and

priorit y inversion is implement ed