Docsity

Synchronization Mechanisms: Semaphores and Monitors, Study notes of Computer Science

Partial preview of the text

Download Synchronization Mechanisms: Semaphores and Monitors and more Study notes Computer Science in PDF only on Docsity!

Chapter 2

Chapter 2: Processes & Threads

Part 2

Interprocess Communication (IPC) &

Synchronization

Chapter 2

CS 1550, cs.pitt.edu (originaly modified by Ethan L. Miller and Scott A. Brandt)

Why do we need IPC?

Each process operates sequentially

All is fine until processes want to share data

„

Exchange data between multiple processes

„

Allow processes to navigate

critical regions

„

Maintain proper sequencing of actions in multipleprocesses

These issues apply to threads as well

„

Threads can share data easily (same address space)

„

Other two issues apply to threads

Chapter 2

CS 1550, cs.pitt.edu (originaly modified by Ethan L. Miller and Scott A. Brandt)

Problem: race conditions

„

Cooperating processesshare storage (memory)

„

Both may read and writethe shared memory

„

Problem: can’t guaranteethat read followed by writeis atomic

„

Ordering matters!

„

This can result in erroneousresults!

„

We need to eliminate raceconditions…

R1 <= xR1 = R1+1R1 => x

R3 <= xR3 = R3+1R3 => x

P

P

x=3 x=

R1 <= x R1 = R1+1R1 => x

R3 <= xR3 = R3+1R3 => x

x=6!

Chapter 2

CS 1550, cs.pitt.edu (originaly modified by Ethan L. Miller and Scott A. Brandt)

Critical regions

„

Use critical regions to provide

mutual exclusion

and help fix race conditions

„

Four conditions to provide mutual exclusion

„

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 forever to enter its critical region

Process AProcess B

B blocked

A enters

critical region

B tries to enter

critical region

B enters

critical region

A leaves

critical region

B leaves

critical region

Time

Chapter 2

CS 1550, cs.pitt.edu (originaly modified by Ethan L. Miller and Scott A. Brandt)

Busy waiting: working solution

#define

FALSE

#define

TRUE

#define

N

// # of processes

int turn;

// Whose turn is it?

int interested[N];

// Set to 1 if process j is interested

void enter_region(int process){

int other = 1-process; // # of the other processinterested[process] = TRUE; // show interestturn = process;

// Set it to my turn

while (turn==process && interested[other]==TRUE)

// Wait while the other process runs

} void leave_region (int process){

interested[process] = FALSE; // I

’m no longer interested

Chapter 2

CS 1550, cs.pitt.edu (originaly modified by Ethan L. Miller and Scott A. Brandt)

intn;/

/# ofpr

ocesses

intchoosi

ng[

n]

intnum ber

[

n]

Bakery algorithm for many processes

„

Notation used

„

<<< is lexicographical order on (ticket#, process ID)

„

(a,b) <<< (c,d) if (a<c) or ((a==c) and (b<d))

„

Max(a0,a1,

…

,an-1) is a number k such that k>=ai for all I

„

Shared data

„

choosing initialized to 0

„

number initialized to 0

Chapter 2

CS 1550, cs.pitt.edu (originaly modified by Ethan L. Miller and Scott A. Brandt)

Hardware for synchronization

Prior methods work, but

„

May be somewhat complex

„

Require busy waiting: process spins in a loop waiting forsomething to happen, wasting CPU time

Solution: use hardware

Several hardware methods

„

Test & set: test a variable and set it in one instruction

„

Atomic swap: switch register & memory in one instruction

„

Turn off interrupts: process won

t be switched out unless

it asks to be suspended

Chapter 2

CS 1550, cs.pitt.edu (originaly modified by Ethan L. Miller and Scott A. Brandt)

Code for process P

i

w hi

le (

w hi

le (

Test

AndSet

lock)

/cr

it

icalsect

ion

lock = 0;/

/r

em ai

nderofcode

} Code for process P

i

w hi

le (

w hi

le (

Sw ap(

lock,

/cr

it

icalsect

ion

lock = 0;/

/r

em ai

nderofcode

intl }

ock = 0;

Mutual exclusion using hardware

„

Single shared variable lock

„

Still requires busy waiting,but code is much simpler

„

Two versions

„

Test and set

„

Swap

„

Works for any number ofprocesses

„

Possible problem withrequirements

„

Non-concurrent code can leadto unbounded waiting

Chapter 2

CS 1550, cs.pitt.edu (originaly modified by Ethan L. Miller and Scott A. Brandt)

Critical sections using semaphores

Code for process P

i

w hi

le (

dow n(

m ut

ex)

/cr

it

icalsect

ion

up(

m ut

ex)

/r

em ai

nderofcode

Shared variables Sem aphor }

e m ut

ex;

„

Define a class called Sem aphor

e

„

Class allows more compleximplementations forsemaphores

„

Details hidden from processes

„

Code for individual processis simple

Chapter 2

CS 1550, cs.pitt.edu (originaly modified by Ethan L. Miller and Scott A. Brandt) class Semaphore {

int value;ProcessList pl;void down ();void up (); };

Semaphore codeSemaphore::down (){

value -= 1;if (value < 0) {

// add this process to plSleep (); } } Semaphore::up () {Process P;

value += 1;if (value <= 0) {

// remove a process P// from plWakeup (P); } }

Implementing semaphores with blocking

„

Assume two operations:

„

Sleep(): suspends currentprocess

„

Wakeup(P): allows process Pto resume execution

„

Semaphore is a class

„

Track value of semaphore

„

Keep a list of processeswaiting for the semaphore

„

Operations still atomic

Chapter 2

CS 1550, cs.pitt.edu (originaly modified by Ethan L. Miller and Scott A. Brandt)

Types of semaphores

Two different types of semaphores

„

Counting semaphores

„

Binary semaphores

Counting semaphore

„

Value can range over an unrestricted range

Binary semaphore

„

Only two values possible

„

1 means the semaphore is available

„

0 means a process has acquired the semaphore

„

May be simpler to implement

Possible to implement one type using the other

Chapter 2

CS 1550, cs.pitt.edu (originaly modified by Ethan L. Miller and Scott A. Brandt)

Monitors

„

A

monitor

is another kind of high-level synchronization

primitive

„

One monitor has multiple entry points

„

Only one process may be in the monitor at any time

„

Enforces mutual exclusion - less chance for programming errors

„

Monitors provided by high-level language

„

Variables belonging to monitor are protected from simultaneousaccess

„

Procedures in monitor are guaranteed to have mutual exclusion

„

Monitor implementation

„

Language / compiler handles implementation

„

Can be implemented using semaphores

Chapter 2

CS 1550, cs.pitt.edu (originaly modified by Ethan L. Miller and Scott A. Brandt)

Condition variables in monitors

Problem: how can a process wait inside a monitor?

„

Can

t simply sleep: there

s no way for anyone else to enter

„

Solution: use a condition variable

Condition variables support two operations

„

Wait(): suspend this process until signaled

„

Signal(): wake up exactly one process waiting on thiscondition variable

„

If no process is waiting, signal has no effect

„

Signals on condition variables aren

’

t

“

saved up

”

Condition variables are only usable within monitors

„

Process must be in monitor to signal on a conditionvariable

„

Question: which process gets the monitor after Signal()?

Chapter 2

CS 1550, cs.pitt.edu (originaly modified by Ethan L. Miller and Scott A. Brandt)

Monitor semantics

„

Problem: P signals on condition variable X, waking Q

„

Both can

’

t be active in the monitor at the same time

„

Which one continues first?

„

Mesa semantics

„

Signaling process (P) continues first

„

Q resumes when P leaves the monitor

„

Seems more logical: why suspend P when it signals?

„

Hoare semantics

„

Awakened process (Q) continues first

„

P resumes when Q leaves the monitor

„

May be better: condition that Q wanted may no longer hold when P leaves themonitor