Docsity

Synchronization in Computer Systems: Controlling Access to Shared Resources, Slides of Computer Science

Partial preview of the text

Download Synchronization in Computer Systems: Controlling Access to Shared Resources and more Slides Computer Science in PDF only on Docsity!

CSE 410Computer Systems

L

t^

S

h

i^

ti

Lecture 18 – Synchronization

SynchronizationSynchronization •^

Threads cooperate in multithreaded programs–

to share resources, access shared data structures

-^

e.g., threads accessing a memory cache in a web server

-^

also, to coordinate their execution

-^

e.g., a disk reader thread hands off blocks to a network writer threadthrough a circular buffer

diskreader

networkwriterthread

thread

circular buffer

3

Shared resourcesShared

resources

-^

We’ll focus on coordinating access to shared

g

resources– basic problem:

  • two concurrent threads are accessing a shared

variable

  • if the variable is read/modified/written by both• if the variable is read/modified/written by both

threads, then access to the variable must becontrolled

  • otherwise, unexpected results may occur

5

The classic exampleThe

classic example

-^

Suppose we have to implement a function to

pp

p

withdraw money from a bank account:^ int

withdraw(account,

amount)

{

int

balance

=

get_balance(account);

b^

l^

t

balance

-=

amount;

put_balance(account,

balance);

return

balance;

}

-^

Now suppose that you and your S.O. share a bankaccount with a balance of $100.00– what happens if you both go to separate ATM– what happens if you both go to separate ATM

machines, and simultaneously withdraw $10.00from the account?

6

Interleaved schedulesInterleaved

schedules

-^

The problem is that the execution of the two threads

b

i t

l^

d

i^

ti^

h d li

can be interleaved, assuming preemptive scheduling:

balance

=

get_balance(account);

balance

-=

amount;

t^

t^

it h

balance

=

get_balance(account);

balance

-=

amount;

put_balance(account,

balance);

Execution sequenceas seen by CPU

context switchcontext switch

-^

What’s the account balance after this sequence?

h ’

h

th

b

k

put_balance(account,

balance);

who’s happy, the bank or you?

-^

How often is this unfortunate sequence likely tooccur?

8

The crux of the matterThe

crux of the matter

•^

The problem is that two concurrent threads (or processes)access a shared resource (account) without anysynchronization– creates a

race condition

  • output is non-deterministic, depends on timing

•^

We need mechanisms for controlling access to sharedresources in the face of concurrency

y

  • so we can reason about the operation of programs
    • essentially, re-introducing determinism

•^

Synchronization is necessary for any shared data

-^

Synchronization is necessary for any shared datastructure– buffers, queues, lists, hash tables, scalars, …

9

Mutual exclusionMutual

exclusion

•^

We want to use mutual exclusion to synchronize access toshared resources

-^

Mutual exclusion makes reasoning about programbehavior easier– making reasoning easier leads to fewer bugs

-^

Code that uses mutual exclusion to synchronize itsexecution is called a critical section– only one thread at a time can execute in the critical

section

  • all other threads are forced to wait on entry

all other threads are forced to wait on entry

  • when a thread leaves a critical section, another can

enter

11

Critical section requirementsCritical

section requirements

-^

Critical sections have the following requirements– mutual exclusion

  • at most one thread is in the critical section
    • progress
      • if thread T is outside the critical section, then T cannot

prevent thread S from entering the critical section

  • bounded waiting (no starvation)
    • if thread T is waiting on the critical section, then T will

eventually enter the critical section

  • assumes threads eventually leave critical sections

f i

?

  • vs. fairness?
    • performance
      • the overhead of entering and exiting the critical section is

small with respect to the work being done within itsmall with respect to the work being done within it

12

LocksLocks

-^

A lock is an object (in memory) that provides thefollowing two operations:^ – acquire()

: a thread calls this before entering a critical section

  • release()

: a thread calls this after leaving a critical section

release()

:^ a thread calls this after leaving a critical section

-^

Threads pair up calls to

acquire()

and

release()

  • between

acquire()

and

release()

, the thread holds the lock

  • acquire()

does not return until the caller holds the lock

-^

at most one thread can hold a lock at a time (usually)

  • so: what can happen if the calls aren’t paired? -^

Two basic flavors of locks– spinlock

bl

ki

(^

k^

“^

t^

”)

  • blocking (a.k.a. “mutex”)

14

Using locksUsing

locks

int

withdraw(account,

amount)

{

acquire(lock)balance

=

get

balance(account);

acquire(lock);balance

=

get_balance(account);

balance

-=

amount;

b^

l^

(^

b^

l^

)

balance

get_balance(account);

balance

-=

amount;

put

balance(account

balance);

acquire(lock)

itical r

ection

put_balance(account,

balance);

release(lock);return

balance;

}

balance

=

get_balance(account);

balance

-=

amount;

put_balance(account,

balance);

release(lock);

cr

se

Wh t h

h

t i

t^

i^

th

l^

k?

put_balance(account,

balance);

release(lock);

-^

What happens when green tries to acquire the lock?

-^

Why is the “return” outside the critical section?– is this ok?

is this ok?

15

Implementing locks (cont )Implementing

locks (cont.)

•^

Problem is that implementation of locks has critical

ti^

t^

sections, too!– the acquire/release must be

atomic

  • atomic == executes as though it could not be

interruptedinterrupted

  • code that executes “all or nothing”

•^

Need help from the hardware

atomic instr ctions

  • atomic instructions
    • test-and-set, compare-and-swap, …• see text for examples di

bl /

bl

i t

t

  • disable/reenable interrupts
    • to prevent context switches• crude – and can only be done in the kernel

17

Summary so farSummary

so far

•^

Synchronization can be provided by locks, semaphores,monitors, messages …

-^

Locks are the lowest-level mechanism– very primitive in terms of semantics – error-prone

y p

p

  • implemented by spin-waiting (crude) or by disabling

interrupts (also crude, and can only be done in thekernel)

•^

In our next exciting episode …– semaphores are a slightly higher level abstraction

  • less crude implementation too• less crude implementation too
    • monitors are significantly higher level
      • utilize programming language support to reduce

errors

18

Blocking in semaphoresBlocking

in semaphores

-^

Each semaphore has an associated queue of threads

h^

P(

) i

ll d b

th

d

  • when P(sem) is called by a thread,
    • if sem was “available” (>0), decrement sem and let thread

continueif sem was “unavailable” (< 0) place thread on associated

  • if sem was “unavailable” (<=0), place thread on associated

queue; dispatch some other runnable thread

  • when V(sem) is called by a thread
    • if thread(s) are waiting on the associated queue unblock one• if thread(s) are waiting on the associated queue, unblock one
      • place it on the ready queue– might as well let the “V-ing” thread continue execution– or not, depending on priority

,^

p^

g^

p^

y

  • otherwise (when no threads are waiting on the sem),

increment sem

  • the signal is “remembered” for next time P(sem) is called -^

Semaphores thus have history

20

Abstract implementationAbstract

implementation

  • P/wait(sem)
    • acquire “real” mutual exclusion
      • if sem is “available” (>0), decrement sem; release “real”

mutual exclusion; let thread continueth

i^

l^

th

d^

i t d

l^

“^

l”

  • otherwise, place thread on associated queue; release “real”

mutual exclusion; run some other thread

  • V/signal(sem)

i^

“^

l”

t^

l^

l^

i

  • acquire “real” mutual exclusion
    • if thread(s) are waiting on the associated queue, unblock one

(place it on the ready queue)if no threads are on the queue sem is incremented

  • if no threads are on the queue, sem is incremented

» the signal is “remembered” for next time P(sem) is called

  • release “real” mutual exclusion

[th

“V i

” th

d

ti^

ti^

i^

t d]

  • [the “V-ing” thread continues execution or is preempted]

21