F undamen tal Structures of Computer Science I I 15-212-ML - - PDF document

f undamen tal structures of computer science i i 15 212
SMART_READER_LITE
LIVE PREVIEW

F undamen tal Structures of Computer Science I I 15-212-ML - - PDF document

F undamen tal Structures of Computer Science I I 15-212-ML F all 1998 CONCURRENCY Concurrency Op erations in a p rogram a re if they b e concurrent c ould executed in pa rallel. Concurrent p rograms a re


slide-1
SLIDE 1 F undamen tal Structures
  • f
Computer Science I I 15-212-ML F all 1998 CONCURRENCY
slide-2
SLIDE 2 Concurrency Op erations in a p rogram a re concurrent if they c
  • uld
b e executed in pa rallel. Concurrent p rograms a re inherently nondeterministic. Concurrent p rogramming languages p rovide abstraction mechanisms fo r concurrency , with less
  • verhead
than using system-level p ro cesses. 2
slide-3
SLIDE 3 F
  • rcing
Sequential Op erations Being fo rced to have sequential
  • p
erations can have disatrous eects fo r inherently concurrent applications. Example: the Unix xrn \lost connection to remote news server" feature. 3
slide-4
SLIDE 4 Natural Places fo r Concurrent Programming
  • Interactive
systems such as windo w managers and GUIs. User interaction can b e complex.
  • A
sp readsheet might p rovide an edito r, a windo w fo r graphical displa ys
  • f
data, and even a sp eech interface.
  • Many
applications have \deadtime" b et w een input events when running.
  • If
application is
  • utput
intensive, concurrency can mak e it resp
  • nsive
to input.
  • Distributed
systems { each no de has its
  • wn
state and control
  • w.
Anything involving a net w
  • rk.
  • Client-server
p roto cols. 4
slide-5
SLIDE 5 Language Supp
  • rt
Abstraction is essential to writing and maintaining soft w a re When it comes to concurrency , most languages do not p rovide useful abstractions Ra w p ro cess creation using fo rk() is p rovided in C 5
slide-6
SLIDE 6 Reasoning Ab
  • ut
Languages In SML there is a clean semantics that aids
  • ur
reasoning
  • `
e 1 , ! true
  • `
e 2 , ! v
  • `
if e 1 then e 2 else e 2 , ! v With references, reasoning b ecomes mo re complicated let val memo = ref (fn () => raise Impossible) fun s'() = let val r = s() in memo := (fn () => r); r end in memo := s'; fn () => (!memo)() end 6
slide-7
SLIDE 7 Concurrent Programming is Ha rd Sequential p rograms a re deterministic let val x = ref in x := !x + 1; x := !x + 2; print (!x) end Reasoning required when p rogramming with concurrency is much mo re complicated let val x = ref in (x := !x + 1) k (x := !x + 2); print (!x) end 7
slide-8
SLIDE 8 Ingredients fo r Concurrency
  • A
mechanism fo r intro ducing sequential threads
  • f
control,
  • r
p ro cesses
  • A
w a y fo r p ro cesses to communicate
  • A
mechanism fo r p ro cesses to synchronize to restrict
  • rder
  • f
execution and limit nondeterminism 8
slide-9
SLIDE 9 Flavo rs
  • f
Concurrent Language Sha red-memo ry
  • Rely
  • n
imp erative features fo r interp ro cess communication
  • Sepa
rate synchronization p rimitives to control access to sha red state.
  • Example:
Java Message-passing
  • Unied
mechanism fo r synchronization and communication
  • Example:
CML 9
slide-10
SLIDE 10 Interference let val x = ref in (x := !x + 1) k (x := !x + 2); print (!x) end Interference can
  • ccur
when t w
  • p
ro cesses a re accessing critical regions
  • f
co de where assignments a re made Synchronization p rovides the mechanism fo r avoiding interference, b y allo wing a p ro cess to
  • btain
a lo ck in a critical region. 10
slide-11
SLIDE 11 Deadlo ck Consider the follo wing schematic
  • f
p ro cesses P and Q: P: acquire A; acquire B; compute; release B; release A; Q: acquire B; acquire A; compute; release A; release B; This can deadlo ck with P holding the lo ck
  • n
A and Q holding the lo ck
  • n
B. 11
slide-12
SLIDE 12 Livelo ck No w consider P and Q dened as: P: Q: l: acquire A; l: acquire B; if (B is held) if (A is held) then (release A; goto l) then (release B; goto l) else acquire B else acquire A compute compute release B; release A release A; release B What might happ en here? 12
slide-13
SLIDE 13 Threads in Java public interface Runnable f public abstract void run(); g public class Thread implements Runnable f public Thread(); public Thread(String name); ... public void run(); public void start() thro ws IllegalThreadStateException; public nal void stop(); public nal void suspend() thro ws SecurityException; public nal void resume() thro ws SecurityException; ... g 13
slide-14
SLIDE 14 Threads in Java (con t) class PrimeThread extends Thread f long minPrime; PrimeThread(long minPrime) f this.minPrime = minPrime; g public void run() f // compute p rimes
  • minPrime
... g g PrimeThread p = new PrimeThread(101); p.start(); 14
slide-15
SLIDE 15 Threads in Java (con t)
  • A
synchronized metho d acquires a lo ck b efo re it executes.
  • If
a va riable is ever to b e assigned b y
  • ne
thread and used b y another, all accesses to that va riable should b e synchronized.
  • Lo
cking is ca rried
  • ut
using monito rs in the JVM.
  • Synchronization
mak es metho ds and blo cks atomic.
  • Deadlo
cking is not p revented. 15
slide-16
SLIDE 16 Threads in Java (con t) public class Box f p rivate Object boxContents; public synchronized Object get() f Object contents = boxContents; boxContents = null; return contents; g public synchronized boolean put(Object contents)f if (boxContents != null) return false; boxContents = contents; return true; g g 16
slide-17
SLIDE 17 Sha red Memo ry Mo del
  • Promotes
eciency , but not co rrectness
  • Requires
\defensive p rogramming" (p rotect y
  • ur
data from interference).
  • P
  • r
t with value-o riented p rogramming (ML) 17
slide-18
SLIDE 18 Message-P assing Languages
  • Pro
cesses communicate b y sending messages across channels.
  • The
communication ma y either b e blo cking (o r synchronous)
  • r
non-blo cking (asynchronous) [4 p
  • ssibilities]
  • Mailb
  • x
metapho r: In asynchronous send,
  • nce
the letter is in the mailb
  • x,
the sender can p ro ceed with
  • ther
tasks.
  • T
elephone metapho r: In synchronous send, the sender is tied up until his message is received.
  • Synchr
  • nous
message p assing is e asier to r e ason ab
  • ut.
18
slide-19
SLIDE 19 Basic CML Primitives: Threads A thread is a CML p ro cess. Initially , there is a single thread but mo re can b e created using spawn: val spawn : (unit
  • >
unit)
  • >
thread id
  • Creates
a new thread to evaluate the function.
  • The
numb er
  • f
threads is unb
  • unded.
  • Since
threads a re rep resented b y ML values, their sto rage can b e recycled b y the ga rbage collecto r. 19
slide-20
SLIDE 20 Basic CML Primitives: Channels F
  • r
threads to b e useful, w e need w a ys to communicate b et w een them. F
  • r
communicating values
  • f
t yp e 'a, CML p rovides t yp e 'a chan The send and receive
  • p
erations a re val recv : 'a chan
  • >
'a val send : ('a chan * 'a)
  • >
unit Message passing is synchronous 20
slide-21
SLIDE 21 Basic CML Primitives: Channels (con t) When a thread executes a send
  • r
receive
  • n
a channel, it blo cks until some
  • ther
thread
  • ers
the complementa ry communication. The message is then passed from sender to receiver, and the threads continue. Message passing involves b
  • th
communication and synchronization 21
slide-22
SLIDE 22 Example: Reference Cells As a simple example
  • f
channels, as w ell as client-server p roto cols, w e'll implement the follo wing signature fo r mutable cells: signature CELL = sig t yp e 'a cell val cell : 'a
  • >
'a cell val get : 'a cell
  • >
'a val put : 'a cell * 'a
  • >
unit end 22
slide-23
SLIDE 23 Example: Reference Cells (con t) structure Cell :> CELL = struct datat yp e 'a request = GET | PUT
  • f
'a datat yp e 'a cell = CELL
  • f
freqCh:'a request CML.chan, replyCh:'a CML.chang fun get (CELLfreqCh, replyChg) = (CML.send (reqCh, GET); CML.recv replyCh) fun put (CELLfreqCh, ...g, x) = CML.send (reqCh, PUT x) ... end 23
slide-24
SLIDE 24 Example: Reference Cells (con t) structure Cell :> CELL = struct datat yp e 'a request = GET | PUT
  • f
'a datat yp e 'a cell = CELL
  • f
freqCh:'a request CML.chan, replyCh:'a CML.chang fun cell x = let val reqCh = CML.channel() val replyCh = CML.channel() fun loop x = (case (CML.recv reqCh)
  • f
GET => (CML.send (replyCh, x); loop x) | (PUT x') => loop x') in CML.spawn (fn () => loop x); CELL freqCh = reqCh, replyCh = replyChg end fun get (CELLfreqCh, replyChg) = (CML.send (reqCh, GET); CML.recv replyCh) fun put (CELLfreqCh, ...g, x) = CML.send (reqCh, PUT x) end 24
slide-25
SLIDE 25 Example: Reference Cells (con t) This is an example
  • f
client-server st yle
  • f
concurrent p rogramming. Why is the implementation co rrect? Why can't multiple clients interfere with each
  • ther,
and receive each
  • ther's
messages, since they a re communicating
  • n
the same channel? 25
slide-26
SLIDE 26 Example: Streams fun nats start = let val ch = CML.channel() fun count i = (CML.send(ch, i); count(i+1)) in CML.spawn (fn () => count start); ch end 26
slide-27
SLIDE 27 Sieve
  • f
Eratosthenes fun filter (p, inCh) = let val
  • utCh
= CML.channel(); fun loop () = let val i = CML.recv inCh in if ((i mod p) <> 0) then CML.send (outCh, i) else (); loop() end in CML.spawn loop;
  • utCh
end 27
slide-28
SLIDE 28 Sieve
  • f
Eratosthenes (con t) fun sieve() = let val primes = CML.channel() fun head ch = let val p = CML.recv ch in CML.send (primes, p); head (filter (p, ch)) end in CML.spawn (fn () => head (nats 2)); primes end Ho w do these streams dier from those w e built using susp ensions? 28
slide-29
SLIDE 29 Datao w Net w
  • rks
This is an example
  • f
a datao w net w
  • rk,
where the data moves from
  • ne
p ro cess to another. Simplest example is pip eline where data moves along a chain
  • f
p ro cesses. 29
slide-30
SLIDE 30 The Fib
  • nacci
Net w
  • rk
[Picture
  • f
net w
  • rk
here] 30
slide-31
SLIDE 31 Fib
  • nacci
Net w
  • rk
fun fibchannel () = let val
  • utCh
= CML.channel() val c1 = CML.channel() and c2 = CML.channel() and c3 = CML.channel() val c4 = CML.channel() and c5 = CML.channel() in delay (SOME 0) (c4, c5); copy (c2, c3, c4); add (c3, c5, c1); copy (c1, c2,
  • utCh);
CML.send (c1, 1);
  • utCh
end 31
slide-32
SLIDE 32 Fib
  • nacci
Net w
  • rk
(con t) Implemented using innitely lo
  • ping
threads: val forever : 'a
  • >
('a
  • >
'a)
  • >
unit fun forever init f = let fun loop s = loop (f s) in igno re (CML.spawn (fn () => loop init)) end 32
slide-33
SLIDE 33 Fib
  • nacci
Net w
  • rk
(con t) fun add (inCh1, inCh2,
  • utCh)
= forever () (fn () => CML.send (outCh, (CML.recv inCh1) + (CML.recv inCh2))) fun delay init (inCh,
  • utCh)
= forever init (fn NONE => SOME(CML.recv inCh) | (SOME x) => (CML.send(outCh, x); NONE)) fun copy (inCh,
  • utCh1,
  • utCh2)
= forever () (fn () => let val x = CML.recv inCh in CML.send(outCh1, x); CML.send(outCh2, x) end) 33
slide-34
SLIDE 34 Fib
  • nacci
Net w
  • rk:
A Bug fun fibchannel () = let val
  • utCh
= CML.channel() val c1 = CML.channel() and c2 = CML.channel() and c3 = CML.channel() val c4 = CML.channel() and c5 = CML.channel() in delay (SOME 0) (c4, c5); copy (c2, c4, c3); add (c3, c5, c1); copy (c1, c2,
  • utCh);
CML.send (c1, 1);
  • utCh
end 34
slide-35
SLIDE 35 Fib
  • nacci
Net w
  • rk:
A Bug So, deadlo ck can b e very ha rd to gua rd against. The language can help: intro duce nondeterminism in the
  • rder
  • f
blo cking communication
  • p
erations. Leads us to events 35
slide-36
SLIDE 36 Events CML p rovides the t yp e constructo r fo r abstract synchronous
  • p
erations: t yp e 'a event An
  • event
returns a value
  • f
t yp e
  • when
it is synchronized
  • n.
36
slide-37
SLIDE 37 Events (con t) Events allo w us to manipulate multiple concurrent
  • p
erations without explicitly synchronizing
  • n
any sp ecic
  • ne.
Enables us to reason ab
  • ut
and manipulate the nondeterminism in a p rogram select [ recvEvt chan1, recvEvt chan2 ] The thread blo cks at the select statement, w aiting to receive a message from either channel 37
slide-38
SLIDE 38 Basic Event Op erations val sendEvt : ('a chan * 'a)
  • >
unit event val recvEvt : 'a chan
  • >
'a event val wrap : 'a event * ('a->'b)
  • >
'b event val select : 'a event list
  • >
'a The wrap function enables us to build up event values 38
slide-39
SLIDE 39 Events in Java Events a re \b roadcast" and va rious classes
  • f
events can b e subscrib ed to b y \listening" to the b roadcast channel public abstract interface MouseListener extends EventListener f public abstract void mouseClicked (MouseEvent e); public abstract void mouseEntered (MouseEvent e); public abstract void mouseExited (MouseEvent e); public abstract void mousePressed (MouseEvent e); public abstract void mouseReleased (MouseEvent e); g Do es not supp
  • rt
selection from a dynamically changing set
  • f
events. 39
slide-40
SLIDE 40 Example: Reference Cells Using Events datat yp e 'a cell = CELL
  • f
fgetCh:'a CML.chan, putCh:'a CML.chang fun get (CELLfgetCh, ...g) = CML.recv getCh fun put (CELLfputCh, ...g, x) = CML.send (putCh, x) fun cell x = let val getCh = CML.channel() val putCh = CML.channel() fun loop x = select [ wrap (sendEvt(getCh, x), fn () => loop x), wrap (recvEvt putCh, loop) ] in CML.spawn (fn () => loop x); CELL fgetCh = getCh, putCh = putChg end 40
slide-41
SLIDE 41 Concurrency and Computation Concurrency can enable mo re p
  • w
erful computation. Recall that there is no w a y to compute the disjunction
  • f
t w
  • semi-decision
p ro cedures in SML. Using pa rallel computation, ho w ever, w e can. Ho w? 41
slide-42
SLIDE 42 P a rallel Or & Semi-Decision Pro cedures fun parallelOr (p, q) x = let val chp = CML.channel() val chq = CML.channel() fun decide pred ch = if pred(x) then CML.send(ch, true) else () in CML.spawn (fn () => decide p chp); CML.spawn (fn () => decide q chq); CML.select [ CML.recvEvt chp, CML.recvEvt chq ] end 42
slide-43
SLIDE 43 Reference/Ackno wledgement Most
  • f
the material p resented here has b een adapted from the manuscript Concurr ent Pr
  • gr
amming in ML b y John Repp y . The CML co de in these examples is cop yrighted, (c) 1998 b y Bell Labs, Lucent T echnologies. 43