CSE 513 I ntroduction to Operating Systems Class 3 - I - - PowerPoint PPT Presentation

cse 513 i ntroduction to operating systems class 3 i
SMART_READER_LITE
LIVE PREVIEW

CSE 513 I ntroduction to Operating Systems Class 3 - I - - PowerPoint PPT Presentation

CSE 513 I ntroduction to Operating Systems Class 3 - I nterprocesses Communication & Synchronization Jonathan Walpole Dept. of Comp. Sci. and Eng. Oregon Health and Science University 1 Race conditions What is a race condition?


slide-1
SLIDE 1

1

CSE 513 I ntroduction to Operating Systems Class 3 - I nterprocesses Communication & Synchronization

Jonathan Walpole

  • Dept. of Comp. Sci. and Eng.

Oregon Health and Science University

slide-2
SLIDE 2

2

Race conditions

  • What is a race condition?

t wo or more processes have an inconsist ent view of a

shared memory region (I .e., a variable)

  • Why do race conditions occur?

values of memory locat ions replicat ed in regist ers during

execut ion

cont ext swit ches at arbit rary t imes during execut ion processes can see “st ale” memory values in regist ers

  • What solutions can we apply?

prevent cont ext swit ches by prevent ing int errupt s? make processes coordinat e wit h each ot her t o ensure

mut ual exclusion in accessing “crit ical sect ions” of code

slide-3
SLIDE 3

3

Counter increment race condition

I ncrementing a counter (load, increment, store) Context switch can occur af ter load and bef ore increment!

slide-4
SLIDE 4

4

Mutual exclusion conditions

  • No two processes simultaneously in critical region
  • No assumptions made about speeds or numbers of CPUs
  • No process running outside its critical region may block

another process

  • No process must wait f orever to enter its critical region
slide-5
SLIDE 5

5

Critical regions with mutual exclusion

Mutual exclusion using critical regions

slide-6
SLIDE 6

6

How can we implement mutual exclusion?

What about using a binary “lock” variable in

memory and having processes check it and set it bef ore entry to critical regions?

Many computers have some limited hardware

support f or setting locks

“At omic” Test and Set Lock inst r uct ion “At omic” compar e and swap oper at ion

Solves the problem of

Expr essing int ent ion t o ent er C.S. Act ually set t ing a lock t o pr event concur r ent access

slide-7
SLIDE 7

7

Test and Set Lock

Test- and- set does two things atomically:

Test a lock (whose value is r et ur ned) Set t he lock

Lock obtained when the return value is FALSE I f TRUE, someone already had the lock (and

still has it)

lock = {TRUE , FALSE}

Test_var

  • 1. extract value
  • 2. Set TRUE
slide-8
SLIDE 8

8

Test and Set Lock

FALSE Lock

slide-9
SLIDE 9

9

Test and Set Lock

P1

FALSE Lock

slide-10
SLIDE 10

10

Test and Set Lock

P1

Lock FALSE FALSE = Lock Available!!

slide-11
SLIDE 11

11

Test and Set Lock

TRUE Lock FALSE

P1

slide-12
SLIDE 12

12

Test and Set Lock

TRUE Lock FALSE

P1

slide-13
SLIDE 13

13

Test and Set Lock

TRUE Lock

P1 P2 P3 P4

TRUE TRUE TRUE TRUE TRUE TRUE

slide-14
SLIDE 14

14

Test and Set Lock

TRUE Lock

P1 P2 P3 P4

TRUE TRUE TRUE TRUE TRUE TRUE

slide-15
SLIDE 15

15

Test and Set Lock

TRUE Lock

P1 P2 P3 P4

TRUE TRUE TRUE TRUE TRUE TRUE

slide-16
SLIDE 16

16

Test and Set Lock

FALSE Lock

P1 P2 P3 P4

TRUE TRUE TRUE TRUE TRUE TRUE

slide-17
SLIDE 17

17

Test and Set Lock

FALSE Lock

P1 P2 P3 P4

TRUE FALSE

slide-18
SLIDE 18

18

Test and Set Lock

FALSE Lock

P1 P2 P3 P4

TRUE FALSE

slide-19
SLIDE 19

19

Test and Set Lock

TRUE Lock

P1 P2 P3 P4

TRUE TRUE TRUE TRUE

slide-20
SLIDE 20

20

Critical section entry code with TSL

1 repeat 2 while(TSL(lock)) 3 no-op; 4 critical section 5 Lock = FALSE; 6 remainder section 7 until FALSE 1 repeat

  • while(TSL(lock))

3 no-op; 4 critical section 5 Lock = FALSE; 6 remainder section 7 until FALSE

J I Guaranteed that only one process returns with FALSE when a lock is returned to the system and others are waiting to act on the lock

slide-21
SLIDE 21

21

Generalized primitives f or critical sections

  • Thus f ar, the solutions have used busy waiting

a process consumes CP

U resources t o evaluat e when a lock becomes f ree

  • n a single CP

U syst em busy wait ing prevent s t he lock holder f rom running, complet ing t he crit ical sect ion and releasing t he lock!

it would be bet t er t o block inst ead of busy wait (on a

single CP U syst em)

  • Blocking synchronization primitives

sleep – allows a process t o sleep on a condit ion wakeup – allows a process t o signal anot her process

t hat a condit ion it was wait ing on is t rue

but how can t hese be implement ed?

slide-22
SLIDE 22

22

Blocking synchronization primitives

  • Sleep and wakeup are system calls

OS can implement t hem by managing a dat a st ruct ure t hat

records who is blocked and on what condit ion

but how can t he OS access t hese dat a st ruct ures

at omically?

  • Concurrency in the OS: context switches and interrupts

t he OS can arrange not t o perf orm a cont ext swit ch while

manipulat ing it s dat a st ruct ures f or sleep and wakeup

but what about int errupt s? what if int errupt handlers manipulat e t he sleep and wakeup

dat a st ruct ures? What if t hey need synchronizat ion?

how can t he OS synchronize access t o it s own crit ical

sect ions?

slide-23
SLIDE 23

23

Disabling interrupts

  • Disabling interrupts in the OS vs disabling interrupts in

user processes

why not allow user processes t o disable int errupt s? is it ok t o disable int errupt s in t he OS? what precaut ions should you t ake?

slide-24
SLIDE 24

24

Generic synchronization problems

slide-25
SLIDE 25

25

Producer/ Consumer with busy waiting

process producer{ while(1){ //produce char c while (count==n) no_op; buf[InP] = c; InP = InP + 1 mod n count++; } } process consumer{ while(1){ while (count==0) no_op; c = buf[OutP]; OutP = OutP + 1 mod n count--; //consume char } } 2 3 n-1 … Global variables: char buf[n] int InP, OutP; // [0-n-1] int count

slide-26
SLIDE 26

26

Problems with busy waiting solution

  • Producer and consumer can’t run at the same time
  • Count variable can be corrupted if context switch occurs

at the wrong time

  • Bugs dif f icult to track down
slide-27
SLIDE 27

27

Producer/ Consumer with blocking

process producer{

  • while(1){
  • //produce char c
  • if (count==n)
  • sleep(full);
  • buf[InP] = c;
  • InP = InP + 1 mod n
  • count++;
  • if (count == 1)
  • wakeup(empty);
  • }

} process consumer{

  • while(1){
  • while (count==0)
  • sleep(empty);
  • c = buf[OutP];
  • OutP = OutP + 1 mod n
  • count--;
  • if (count == n-1)
  • wakeup(full);
  • //consume char
  • }

} 1 2 3 n-1 … Global variables: char buf[n] int InP, OutP; // [0-n-1] int count

slide-28
SLIDE 28

28

Problems with the blocking solution

  • Count variable can be corrupted
  • I ncrements or decrements may be lost
  • Both processes may sleep f orever
  • Buf f er contents may be over- written
  • Code that manipulates count must be made a critical

section and protected using mutual exclusion

  • Sleep and wakeup must be implemented as system calls
  • OS must use synchronization mechanisms (TSL or

interrupt disabling) in its implementation of sleep and wake- up … I .e., the critical sections of OS code that manipulate sleep/ wakeup data structures must be protected using mutual exclusion

slide-29
SLIDE 29

29

Semaphores

An abstract data type that can be used f or

condition synchronization and mutual exclusion

I nteger variable with two operations:

down (sema_var )

decr ement sema_var by 1, if possible if not possible, “wait ” unt il possible

up(sema_var )

incr ement sema_var by 1

Both up() and down() are assumed to be atomic

made t o be at omic by OS implement at ion

slide-30
SLIDE 30

30

Semaphores

There are multiple names f or semaphores

Down(S), wait (S), P(S) Up(S), signal(S), V(S)

Semaphore implementations

Binar y semaphor es (mut ex)

  • support mutual exclusion (lock either set or f ree)

Count ing semaphor es

  • support multiple values f or more sophisticated

coordination and controlled concurrent access among processes

slide-31
SLIDE 31

31

Using Semaphores f or Mutex

1 repeat 2 down(mutex); 3 critical section 4 up(mutex); 5 remainder section 6 until FALSE 1 repeat 2 down(mutex); 3 critical section 4 up(mutex); 5 remainder section 6 until FALSE semaphore mutex = 1

slide-32
SLIDE 32

32

Using Semaphores f or Mutex

1 repeat 2 down(mutex); 3 critical section 4 up(mutex); 5 remainder section 6 until FALSE 1 repeat 2 down(mutex); 3 critical section 4 up(mutex); 5 remainder section 6 until FALSE semaphore mutex = 0

slide-33
SLIDE 33

33

Using Semaphores f or Mutex

1 repeat 2 down(mutex); 3 critical section 4 up(mutex); 5 remainder section 6 until FALSE 1 repeat 2 down(mutex); 3 critical section 4 up(mutex); 5 remainder section 6 until FALSE semaphore mutex = 0

slide-34
SLIDE 34

34

Using Semaphores f or Mutex

1 repeat 2 down(mutex); 3 critical section 4 up(mutex); 5 remainder section 6 until FALSE 1 repeat 2 down(mutex); 3 critical section 4 up(mutex); 5 remainder section 6 until FALSE semaphore mutex = 1

slide-35
SLIDE 35

35

Using Semaphores f or Mutex

1 repeat 2 down(mutex); 3 critical section 4 up(mutex); 5 remainder section 6 until FALSE 1 repeat 2 down(mutex); 3 critical section 4 up(mutex); 5 remainder section 6 until FALSE semaphore mutex = 1

Check again to see if it can be decremented

slide-36
SLIDE 36

36

I n class exercise…

I mplement producer consumer solution:

slide-37
SLIDE 37

37

Counting semaphores in producer/ consumer

process producer{

  • while(1){
  • //produce char c
  • down(empty_buffs);
  • buf[InP] = c;
  • InP = InP + 1 mod n
  • up(full_buffs);
  • }

} process consumer{

  • while(1){
  • down(full_buffs);
  • c = buf[OutP];
  • OutP = OutP + 1 mod n
  • up(empty_buffs);
  • //consume char
  • }

} Global variables semaphore full_buffs = 0; semaphore empty_buffs = n; char buff[n]; int InP, OutP;

slide-38
SLIDE 38

38

I mplementing semaphores

Generally, the hardware has some simple

mechanism to support semaphores

Cont r ol over int er r upt s (almost all) Special at omic inst r uct ions in I SA

  • test and set lock
  • compare and swap

Spin- Locks vs. Blocking

Spin-locks (busy wait ing)

  • may waste a lot of cycles on uni- processors

Blocking

  • may waste a lot of cycles on multi- processors
slide-39
SLIDE 39

39

I mplementing semphores

Blocking

Up(semaphore sem) DISABLE_INTS sem.val++; if (sem.val <= 0) { proc = remove next proc from sem.L wakeup(proc); } ENABLE_INTS struct semaphore{ int val; list L; } Down(semaphore sem) DISABLE_INTS sem.val--; if (sem.val < 0){ add proc to sem.L block(proc); } ENABLE_INTS

slide-40
SLIDE 40

40

Semaphores in UNI X

User- accessible semaphores in UNI X are

somewhat complex

each up and down oper at ion is done at omically on an

“ar r ay” of semaphor es.

*********WORDS OF WARNI NG *********

Semaphor es ar e allocat ed by (and in) t he oper at ing

syst em (number based on conf igur at ion par amet er s).

Semaphor es in UNI X ARE A SHARED RESOURCE

AMONG EVERYONE (most implement at ions ar e).

REMOVE your semaphor es af t er you ar e done wit h

t hem.

slide-41
SLIDE 41

41

Typical usage

main(){ int sem_id; sem_id = NewSemaphore(1); ... Down(sem_id); [CRITICAL SECTION] Up (sem_id); ... FreeSemaphore(sem_id); }

slide-42
SLIDE 42

42

Managing your UNI X semaphores

Listing currently allocated ipc resources

ipcs

Removing semaphores

ipcrm -s <sem number>

slide-43
SLIDE 43

43

Classical I PC problems

There are a number of “classic” I PC problems

including:

Pr oducer / Consumer synchr onizat ion The dining philosopher s pr oblem The sleeping bar ber pr oblem The r eader s and wr it er s pr oblem Count ing semaphor es out of binar y semaphor es

slide-44
SLIDE 44

44

Dining Philosophers Problem

  • Five philosophers sit at a table
  • Between each philosopher there is one chopstick
  • Philosophers:
  • Why do they need to synchronize?
  • How should they do it?

while(!dead){ Think(hard); Grab first chopstick; Grab second chopstick; Eat; Put first chopstick back; Put second chopstick back; }

slide-45
SLIDE 45

45

Dining philospher’s solution???

Why doesn’t this work?

#define N 5 Philosopher() { while(!dead){ Think(hard); take_fork(i); take_fork((i+1)% N); Eat(alot); put_fork(i); put_fork((i+1)% N); } }

slide-46
SLIDE 46

46

Dining philospher’s solution (part 1)

slide-47
SLIDE 47

47

Dining philospher’s solution (part 2)

slide-48
SLIDE 48

48

Dining Philosophers

I s this correct? What does it mean f or it to be correct? I s there an easier way?

slide-49
SLIDE 49

49

Sleeping Barber Problem

slide-50
SLIDE 50

50

Sleeping barber

  • Barber

if t here are people wait ing f or a hair cut bring t hem t o

t he barber chair, and give t hem a haircut

else go t o sleep

  • Customer:

if t he wait ing chairs are all f ull, t hen leave st ore. if someone is get t ing a haircut , t hen wait f or t he barber

t o f ree up by sit t ing in a chair

if t he barber is sleeping, t hen wake him up and get a

haircut

slide-51
SLIDE 51

51

Solution to the sleeping barber problem

slide-52
SLIDE 52

52

The readers and writers problem

Readers and writers want to access a database Multiple readers can proceed concurrently Writers must synchronize with readers and

  • ther writers

Maximize concurrency Prevent starvation

slide-53
SLIDE 53

53

One solution to readers and writers

slide-54
SLIDE 54

54

Counting semaphores

A binary semaphore can only take on the values

  • f [0, 1].

Class exercise: create a counting semaphore

(generalized semaphore that we discussed previously) using just a binary semaphore!!

slide-55
SLIDE 55

55

Possible solution

Semaphore S1, S2, S3; // BINARY!! int C = N; // N is # locks down_c(sem){ downB(S3); downB(S1); C = C – 1; if (C<0) { upB(S1); downB(S2); } else { upB(S1); } upB(S3); } up_c(sem){ downB(S1); C = C + 1; if (C<=0) { upB(S2); } upB(S1); }