PROGRAMMING PARADIGMS · PART 2 · SESSION 6, BLOCK 1

Coordination & communication

language constructs for concurrent and distributed programming
  1. 6Asynchronous Programming
  2. 7Multi-Threading
  3. 8Message Passing
  4. 9Failure and Recovery

A sequential program and a slow device

Java// k numbers the portions; the bound of portion k is 250000 + 83333 * (k % 3)
for (int k = 1; k <= 8; k++) {
    // a computation: how many primes are there below the bound of portion k?
    String portion = produceNextPortion(k);
    // a slow device: prints the answer as one line of the page
    processPortionTaken(portion);
}


  
A portion is one line of text: the count of primes below a bound, three bounds in turn so that the portions take different times. The device is slow: a pause of 5 to 25 ms before the line reaches the page. Eight lines in order, 220 ms, most of it waiting for the device.

Dijkstra’s bounded buffer (1965)

E. W. Dijkstra, Cooperating sequential processes, EWD 123, 1965: section 4.3, page 39 of the manuscript. Beside it, the same lines transcribed.

"begin integer number of queuing portions, number of empty positions,
              buffer manipulation;
      number of queuing portions:= 0;
      number of empty positions:= N;
      buffer manipulation:= 1;
      parbegin
      producer: begin
        again 1: produce next portion;
                 P(number of empty positions);
                 P(buffer manipulation);
                 add portion to buffer;
                 V(buffer manipulation);
                 V(number of queuing portions); goto again 1 end;
      consumer: begin
        again 2: P(number of queuing portions);
                 P(buffer manipulation);
                 take portion from buffer;
                 V(buffer manipulation);
                 V(number of empty positions);
                 process portion taken; goto again 2 end
      parend
end" .

EWD 123, 1965, section 4.3. His P is acquire, his V is release.

Two differences from Dijkstra’s program:

  • his processes run for ever; ours stop after eight portions;
  • his buffer has room for N portions; ours for two.

Each loop is an ordinary sequential program.

Four of its lines are the actions we know from the previous slide: produce a portion, put it in the queue, take one out, process it.

These lines call acquire.

Intuitively, acquire waits until something is available, then claims it:

  • the producer, a free place;
  • the consumer, a portion;
  • each, the right to change the queue.

These lines call release.

Intuitively, release makes something available, and a process waiting for it can go on:

  • the producer, a portion;
  • the consumer, a free place;
  • each, the right to change the queue.

Each of those three objects is a semaphore*: a counter, with two operations:

  • acquire waits until the counter is above zero, then takes one off;
  • release adds one.

We come back to them shortly, for what each one allows, but also helps to prevent.

*how a semaphore is built, and what a language offers in its place will be covered in Session 7.

What will be true in every run?

k produced k processed
k produced k processed waiting
producer buffer: room for 2 consumer produce next portion add portion to buffer take portion from buffer process portion taken page appendix
A railway semaphore signal with its arm level: stop
P: stop
The same signal with its arm raised: safe
V: safe

Before programming, a semaphore was a railway signal: an arm on a post, guarding a stretch of track.

P: a train passes the signal only when it shows safe; behind it, the signal is set to stop.

V: the train has left the stretch; the signal is set to safe again.

One train at a time on the stretch.

One signal near Bilthoven, 1938 (Het Utrechts Archief, public domain). The railway is Dijkstra’s own picture, for a semaphore that is 0 or 1: EWD 51.

Java// producer
for (int k = 1; k <= 8; k++) {
    String portion = produceNextPortion(k);
    numberOfEmptyPositions.acquire();     // wait for room
    bufferManipulation.acquire();         // one at a time on the queue
    buffer.addLast(portion);
    bufferManipulation.release();
    numberOfQueuingPortions.release();
}
// consumer
for (int k = 1; k <= 8; k++) {
    numberOfQueuingPortions.acquire();    // wait for a portion
    bufferManipulation.acquire();         // one at a time on the queue
    String portion = buffer.removeFirst();
    bufferManipulation.release();
    numberOfEmptyPositions.release();
    processPortionTaken(portion);
}

What the runs show

  • Every run prints portions 1 to 8 in order, each after it is produced.
  • The order of turns differs from run to run. The program and its input are the same; only the device’s times differ, and the order follows them.
  • The columns record only produced and processed. Up to four portions can be produced and not yet printed: one at the device, two in the queue, one in the producer’s hands, waiting for room.
appendix

A short history of concurrent and distributed programming

hardware operating systems distributed systems languages 1954–57interrupts 1961–62several processors in a machine two cores in a desktop (2005) 2007GPUs for computing 1961time-sharing Dijkstra, semaphores (1965) 1972pipes in Unix 1995POSIX threads 1999–2002ten thousand connections Lamport: logical clocks (1978) 1988–89ViewstampedReplication, Paxos 2002the CAP theorem 2011CRDTs 2019local-firstsoftware monitors,Concurrent Pascal (1974–75) communicating processes (1978) 1996Java, threads Go, async/await, Rust (2009–15) virtual threads (2023) 1965  the semaphore (EWD 123), for waiting and mutual exclusion, in Dijkstra’s THE operating systemPrograms taking turns failed in ways that did not repeat from one run to the next.For years the semaphore was a system call, used by discipline: nothing checked that each acquire had its release. 1974–78  the monitor (Concurrent Pascal) and communicating processes: constructs of a languageThe discipline becomes a construct: the language lets one process at a time into a monitor.1978: processes that share nothing and only send messages (session 8). 1996: Java brings threads to everyone. 1978  no shared clock: Lamport gives machines an order of events to agree on, the basis of replication (session 9)Copies of a service agree by applying the same operations in the same order: Viewstamped Replication, Paxos.2002: the CAP theorem. 2011: CRDTs, copies that may differ for a while and agree in the end. 2005  processors stop getting faster: to use several cores, every programmer must now write concurrent programsSpeed now comes from doing several things at once; from 2007, GPUs too are opened to general computing.Operating systems meanwhile: POSIX threads (1995); one thread watching ten thousand connections (around 2000). 2009–15  Go's channels, async and await, and Rust's Send and Sync, types that reject a data raceTwo pressures, more cores and more waiting. Go: cheap processes, and channels between them.async/await: a wait that does not hold a thread (session 6). Rust: mutual exclusion checked, not trusted. 2023  virtual threads: a thread for each request, made cheapA thread for each request, argued against in the 1990s, is back: the runtime keeps thousands for the price of a few.What an operating system did by discipline, languages took over as constructs: our subject.

Coordination and Communication

Coordination and communication

Coordination: when a process may act depends on what the others have done or are doing.

not before
P waits until Q has acted

Q P

not at the same time
P and Q are never both inside

Q P

Communication: data passes from one process to another.

through memory that both can reach
P writes, Q reads

Q P

by a message
P sends, Q receives

Q P

Coordination and communication in the bounded buffer

Java// producer
for (int k = 1; k <= 8; k++) {
    String portion = produceNextPortion(k);
    numberOfEmptyPositions.acquire();
    bufferManipulation.acquire();
    buffer.addLast(portion);
    bufferManipulation.release();
    numberOfQueuingPortions.release();
}
// consumer
for (int k = 1; k <= 8; k++) {
    numberOfQueuingPortions.acquire();
    bufferManipulation.acquire();
    String portion = buffer.removeFirst();
    bufferManipulation.release();
    numberOfEmptyPositions.release();
    processPortionTaken(portion);
}
  1. not before: the consumer takes no portion before one is produced.
    numberOfQueuingPortions counts the portions in the queue: acquire waits while it is 0, the producer's release adds one.
  2. not before: the producer adds no portion before there is room.
    numberOfEmptyPositions counts the empty places: acquire waits while it is 0, the consumer's release adds one.
  3. not at the same time: the two never change the queue at once.
    bufferManipulation is taken before the queue is touched and given back after.
  4. communication: a portion passes through the queue, memory that both reach.
    addLast in the producer, removeFirst in the consumer.

Correctness: safety and liveness

“Software is hard.”

Donald Knuth

Writing a correct sequential program is already a challenge. For a concurrent or distributed program it is an order of magnitude harder: one input has many executions, and a part can fail while the others go on.

In general, the correctness of a program splits into properties of two kinds.

Safety

Nothing bad ever happens.

A violation happens at one definite moment.

Liveness

Something good eventually happens.

No finite beginning of an execution violates it.

Common correctness properties

propertywhat it saysan example
mutual exclusiontwo processes are never in the same critical section at the same timethe bounded buffer: one at a time on the queuesafety
linearizabilitythe calls answer as if made one at a time, in an order that keeps a call that returned before one that was made latera bank account that many clients use at oncesafety
deadlock freedomno state is ever reached in which each process waits for something that only another can givetwo transfers, each holding one lock and waiting for the other’ssafety
starvation freedomevery process that asks is served in the endevery request to a server gets an answerliveness
eventual consistencyif the requests stop, the copies agree in the endtwo copies of an account on two machinesliveness
appendix

Language support for correctness

For every property, who makes it hold: the language, a library, or the programmer?

the language
(compiler, runtime)
a librarythe programmer
(keywords, discipline)
mutual exclusion
safety
Rust: no way to the data in a Mutex<T> without its lock. Erlang: nothing is shared.locks and semaphores: java.util.concurrentsynchronized, sync.Mutex: every access must lock; nothing checks
starvation freedom
liveness
Go, Erlang interrupt a long computation; JavaScript does notfair locks: new ReentrantLock(true)no long computation on the loop; time limits

This is not a course on concurrency or on distributed systems: it meets their notions through the programming language.

mutual exclusionwhich construct holds the lock, and who checks that it is taken?
failuresin what form does a failure reach the program?
appendix

Overview of Part 2

The questions of Part 2

6At which points of a function's text can control pass to another process, and what represents the suspended computation?
7When two processes can reach the same data, which constructs express mutual exclusion and condition synchronization, and do they compose?
8If processes share no data, what does passing a value from one to the other mean: is it shared, copied, or moved?
9When a fault occurs, in what form does it reach the program, which constructs report it and recover from it, and what remains for the programmer?
Every week: who makes each property hold: the language, a library, or the programmer?

A running example: a bank account

deposit(20) withdraw(50) deposit(10) clients server 100 balance

deposit(n) answers ok

withdraw(n) answers ok or refused

as if one at a time, in some order

From outside, the bank must behave as one sequential machine.
Linearizability: in every execution, the calls can be arranged in one sequence in which each call answers as it would if the calls were made alone, in that order, and a call that returned before another was made comes first.

Serving many clients: one loop, or a thread each

one teller with ticketssession 6 3 4 5 6 set aside 1 2 one request runs at a time a teller for each clientsession 7 100 requests run at the same time

Ten thousand clients: a thread for each, or one loop for all?

Ten thousand clients at once, most of them idle: the C10K problem (Kegel, 1999).

  • A thread for each: ten thousand stacks, and the system switching between threads that only wait.
  • One loop for all: connections that never block, and one call that returns those that are ready: kqueue (Lemon, 2001), epoll (Linux).
running waiting one request runs at a time one loopsession 6 a b c b a c a b c a thread for each clientsession 7 requests run at the same time a b c one client's own program a page in a browser, waiting for its replythe thread stays free for the user time
appendix

Shared memory: threads and lockssession 7

core 1 core 2 core 3 core 4 a million accounts account 1100 account 2250 account 340 account 4900 account 575 account 6310 account 7120 account 860 interest, for every account withdraw(50) deposit(20) several threads, on the same balances
one lock for the whole table account 1100 account 2250 account 340 account 4900 account 575 simple; everyone waits for everyone one lock for each account account 1100 account 2250 account 340 account 4900 account 575 more at once; a transfer needs two the balance is inside its lock 100 there is no other way in
One loop is not enough: the interest on a million accounts would freeze every client, and the machine has several cores. So several threads run at once on the same balances, and two are about to change the same balance at the same time: the one at a time of Dijkstra’s queue.
A lock is held by one thread at a time; the others wait. Left: simple, and everyone waits for everyone. Middle: more runs at once, but a transfer needs two locks (session 7). Right: the only way to the balance is through its lock; a program that forgets it is rejected (Rust).
appendix

Message passing: isolated parts with mailboxessession 8

front accounts 100 record notifier
Each part has a mailbox, a queue of the messages sent to it. The accounts take one message, handle it completely, then take the next: nothing touches the balance in the middle of a withdrawal, and there is no lock.
each part owns its data; the others can only send it messages
senderreceiver sharedboth hold the same thing copiedthe receiver gets a copy handed overthe sender has it no more shared: nothing is copied, but if the thing can change we are back at locks copied: the price is the copying · handed over: the language must stop the sender using it afterwards
appendix

Replication: two copies and a failed linksession 9

Two copies cannot reach each other: what does a copy answer to a client? Refuse to answer, or let them differ?

withdraw(100) copy 1 copy 2 100100 cannot decide now answering cannot decide now 00 ok withdraw(100) ok 100 − 200 = −100 deciding from what it knows: both copies approve, and the balance is negative 5050 refused holding its own share: 50 on each copy, each approves up to 50 without asking
An answer, not a decision: the balance is never wrong, and the client has nothing definitive, neither ok nor refused, for as long as the link is down.
Each copy decides from what it knows; a second client withdraws the same 100 at copy 2. When the link returns, 200 has been paid out of 100. Deposits made on both copies add up afterwards.
Each copy approves up to its share without asking the other: no failure of the link makes the balance negative. The price: a withdrawal of 100 is refused although the bank holds 100.
appendix

Part 2 at a glance

clients front accounts 100 a second copy 100 session 6 one loop session 7 several threads session 8 messages session 9 failure
SESSION 6

What does a program do while it waits, and where is the rest of a function while it waits?

Appendix

The bounded buffer in asynchronous style

k produced k processed

 

Every run prints portions 1 to 8 in order, each after it is produced.

Java// one at a time on the queue: one thread runs all of this
static final ScheduledExecutorService loop =
    Executors.newSingleThreadScheduledExecutor();
// producer
static CompletableFuture<Void> produce(int k) {
    if (k > 8) return done();
    String portion = produceNextPortion(k);
    return queue.put(portion)           // wait for room
        .thenComposeAsync(v -> produce(k + 1), loop);
}
// consumer
static CompletableFuture<Void> consume(int k) {
    if (k > 8) return done();
    return queue.take()                 // wait for a portion
        .thenComposeAsync(p -> processPortionTaken(p), loop)
        .thenComposeAsync(v -> consume(k + 1), loop);
}
back

The animation of the bounded buffer

The diagram of slide 3 is a program: two async functions sharing one array as the queue.

until waits and signal wakes, in the parts of acquire and release.

The device’s time is random: every run differs.

One thread: the turn passes only at an await, so one at a time on the queue needs no semaphore. Session 6.

JavaScript// producer
for (let k = 1; k <= 8; k++) {
  await sleep(PRODUCE[(k - 1) % 3]);  // produce next portion
  const c = chip(k);
  while (queue.length === 2)          // wait for room
    await until('room', producer);
  queue.push(c); place();             // add portion to buffer
  signal('portion');
}
// consumer
for (let k = 1; k <= 8; k++) {
  while (queue.length === 0)          // wait for a portion
    await until('portion', consumer);
  const c = queue.shift(); place();   // take portion from buffer
  signal('room');
  moveTo(c, AT_CONSUMER);
  await sleep(0.8 + Math.random() * 0.9);  // the device
  print(c, k);                        // process portion taken
}
back

Example: the requirements of a bank account

copy 1100 copy 2100 no deposit answered ok is lost no request changes the balance twice the balance is never negative every request gets a definitive answer in the end the copies agree

Liveness: the request gets its answer in the end; the copies agree in the end.

Safety: the three requirements at the balance. Each says never.

back

Language support, property by property

the language
(compiler, runtime)
a librarythe programmer
(keywords, discipline)
mutual exclusionRust: no way to the data in a Mutex<T> without its lock. Erlang: nothing is shared.locks and semaphores: java.util.concurrentsynchronized, sync.Mutex: every access must lock; nothing checks
linearizabilityErlang: a process handles one message at a timeAtomicInteger: each operation, alonetwo such operations in a row are not one: check, then act
deadlock freedomPrevented by none of Java, Rust, Go, Erlang. Go’s runtime detects a total deadlock.tryLock with a time limitone order in which all code takes its locks
starvation freedomGo, Erlang interrupt a long computation; JavaScript does notfair locks: new ReentrantLock(true)no long computation on the loop; time limits
eventual consistencyProvided by no general-purpose language.mergeable data types, such as a set with unionwhich merge is right; when to send again
back

Session 6: Asynchronous Programmingconcurrency on one thread

  • One thread runs all our code. A function that waits gives the thread back.
  • We look at what a language does at an await.

After this session we can explain:

  • where the rest of a function is kept while it waits;
  • why waiting is not running, and why one thread does not rule out a race.

Languages: JavaScript; Python beside it.

back

Session 7: Multi-Threadingshared-memory concurrency: locks, atomic operations, ownership

  • Several threads run our code at the same time, on the same memory.
  • We look at how shared data is protected, who checks that it is, and when nothing needs protecting.

After this session we can explain:

  • why a lock protects only if every access takes it, and how a compiler can check that;
  • why two protected operations, one after the other, are not one protected operation;
  • why a parallel map of a function without effects gives the same result in every execution.

Languages: Java; Rust and OCaml beside it.

Rustlet balance = Arc::new(Mutex::new(100));
let b = Arc::clone(&balance);
let t = thread::spawn(move || {
    *b.lock().unwrap() += 20;
});
t.join().unwrap();
Javalong total = IntStream.rangeClosed(1, N)
    .parallel()
    .mapToLong(Sum::f)
    .sum();
back

Session 8: Message Passingconcurrency without shared memory: channels and actors

  • Processes share no data. They send each other messages, and every message sent arrives.
  • We look at what is addressed (a channel, or a process), and at what sending does to a value.

After this session we can explain:

  • why a process that handles one message at a time needs no lock on its own state;
  • what happens to a value that is sent: shared, copied, or handed over;
  • why messages remove neither the deadlock nor the lost deposit.

Languages: Go; Erlang.

Goportions := make(chan string, 2)
go func() {
    for k := 1; k <= 8; k++ {
        portions <- produce(k)
    }
    close(portions)
}()
for p := range portions {
    process(p)
}
Erlangloop(Balance) ->
    receive
        {deposit, N, From} ->
            From ! ok, loop(Balance + N);
        {withdraw, N, From} when N =< Balance ->
            From ! ok, loop(Balance - N);
        {withdraw, _, From} ->
            From ! refused, loop(Balance)
    end.
back

Session 9: Failure and Recoverydistributed programming: delivery not assumed

  • A message can be lost, a process or a machine can stop, and the rest goes on.
  • We look at the form in which a failure reaches a program, and at what the program can do then.

After this session we can explain:

  • why a process that is slow and a process that has stopped look the same from outside;
  • when a request may be sent again;
  • what a restart gives back, and what it does not.

Languages: Erlang; OCaml.

Erlangask(Account, Request) ->
    Account ! Request,
    receive
        Answer -> Answer
    after 1000 ->
        no_answer
    end.
OCamlmodule Entries = Set.Make (String)
let merge a b = Entries.union a b
back