Lecture 7: Concurrency
Lecture 7 discusses concurrency. It talks about how multicore systems
are driving increasingly concurrent programming, and hot the commonly
used approach to concurrent code, using threads, locks, and shared
mutable state, is problematic. It introduces transaction-based and
message passing models as possible alternatives that might make
concurrent programming simpler in future.
Part 1: Concurrency
The first part of the lecture talks about the implications of multicore
systems on programming. It outlines the need for modern programming
languages to have a well-defined memory model, and outline the memory
model adopted by Java. It talks about the common concurrency model of
threads and shared mutable state protected by locks, and discusses the
limitations and problems inherent in this model. And it starts to
introduce alternative concurrency models that will form the basis for
the discussion in later parts of the lecture.
00:00:00.000
In this lecture, I’d like to move
00:00:03.415
on from discussing memory management and garbage
00:00:05.830
collection, and talk instead about concurrency.
00:00:09.000
In this part, I’ll talk about some
00:00:11.483
implications of multicore hardware on the way
00:00:13.967
we write concurrent programs. In particular,
00:00:16.095
I’ll discuss how memory is arranged in
00:00:18.579
multicore systems and how this affects the
00:00:21.062
threading model for software running on those
00:00:23.545
systems.
00:00:24.000
Then, in the following parts of the
00:00:26.800
lecture, I’ll talk about two alternative approaches
00:00:29.600
to concurrency, using transactions and message passing.
00:00:32.500
And, finally, I’ll talk about the impact
00:00:35.462
of race conditions on concurrent systems.
00:00:39.500
I’d like to begin, though, by talking
00:00:41.923
about some implications of multicore hardware.
00:00:46.000
As we discussed back in Lecture 2,
00:00:49.450
computing systems are increasingly providing multicore support.
00:00:53.000
It’s now difficult to buy uniprocessor systems,
00:00:55.913
and systems with four or eight cores
00:00:58.826
are now mainstream. And systems with up
00:01:01.739
to 64 processor cores, and perhaps more,
00:01:04.652
are readily available.
00:01:06.000
The obvious consequence of this is that
00:01:09.052
parallel computation is now the norm.
00:01:11.668
Perhaps less obvious, though, is that distributed
00:01:14.720
memory is now also commonplace.
00:01:17.000
Each processor core has its own private
00:01:19.725
cache, that is not shared with other
00:01:22.450
cores. And as a result, each processor
00:01:25.175
has its own distinct view of memory.
00:01:28.000
And memory is not always equally accessible
00:01:30.858
to all the processor cores.
00:01:33.000
The figure at the top right of
00:01:35.173
the slide shows an eight core system
00:01:37.346
where each core has its own level
00:01:39.519
1 cache, but pairs of cores share
00:01:41.692
a level 2 cache. And where memory
00:01:43.865
is connected to all of the cores
00:01:46.037
via a shared memory controller hub.
00:01:48.000
The figure at the bottom right,
00:01:50.422
in contrast, shows a system where the
00:01:53.248
cores don’t share cache, and where the
00:01:56.074
memory is physically attached to certain processors.
00:01:59.000
In this case processor cores have direct
00:02:01.480
access to the memory attached to the
00:02:03.959
processor of which they are a part,
00:02:06.439
but can’t directly access other memory.
00:02:08.564
These processors communicate via a hardware message
00:02:11.044
passing layer, if they need to access
00:02:13.524
remote memory, asking the other processor to
00:02:16.003
read from its memory and pass the
00:02:18.483
result back to them.
00:02:20.000
Now, these are examples of the way
00:02:23.019
systems are built. And there are many
00:02:26.038
other examples.
00:02:27.000
What’s important is that memory access is
00:02:31.130
no longer uniform.
00:02:33.000
The different processor cores each have a
00:02:35.473
different view of the contents of memory,
00:02:37.945
due to caching. And the speed at
00:02:40.418
which each core can access a particular
00:02:42.890
value in memory will depend on cache
00:02:45.363
occupancy, and on where in memory that
00:02:47.835
value is physically located. And this can
00:02:50.308
lead to a several-thousand times variation in
00:02:52.781
memory access latency for different values.
00:02:55.000
It’s prohibitively expensive to ensure that all
00:02:58.253
threads, on all cores, see the same
00:03:01.506
view of memory.
00:03:03.000
Rather, to ensure good performance, modern systems
00:03:05.948
allow different processor cores to see inconsistent
00:03:08.897
views of memory. What you see when
00:03:11.845
you read memory will depend what core
00:03:14.794
your program is executing on.
00:03:17.000
And they introduce explicit synchronisation points.
00:03:20.000
Explicit operations that force synchronisation of the
00:03:23.468
view of memory between processors, with each
00:03:26.936
processor providing slightly different primitives to do
00:03:30.405
this.
00:03:31.000
To ensure that programs work portably across
00:03:33.683
the different types of processor, programming languages
00:03:36.367
define their memory model.
00:03:38.000
They need to define what guarantees the
00:03:41.177
language provides around concurrent memory accesses.
00:03:44.000
And the compiler can then turn this
00:03:46.709
into machine code, using the synchronisation primitives
00:03:49.417
provided by the underlying hardware, to ensure
00:03:52.126
consistent behaviour.
00:03:56.000
So what do these memory models look
00:03:59.412
like?
00:04:00.000
Well, the first mainstream language to define
00:04:03.446
an explicit memory model was Java.
00:04:06.500
The Java virtual machine guarantees that changes
00:04:09.031
made to a particular field in an
00:04:11.562
object appear in program order to the
00:04:14.092
thread that made the change.
00:04:16.000
That is, if a single thread writes
00:04:18.495
a value to memory, and then later
00:04:20.990
reads it back, and provided no other
00:04:23.485
threads wrote to the same location,
00:04:25.623
then the value the thread reads will
00:04:28.118
be that which it wrote.
00:04:30.000
And this is what you’d expect.
00:04:34.000
However, if multiple threads read and write
00:04:36.872
to a single field, then Java only
00:04:39.745
guarantees that changes made by one thread
00:04:42.617
become visible to other threads in certain
00:04:45.490
cases.
00:04:46.000
If a thread changes a field that’s
00:04:48.772
marked as volatile, for example, then that
00:04:51.544
change is made atomically, and immediately becomes
00:04:54.316
visible to other threads.
00:04:56.000
But, if a thread changes a field
00:04:58.580
that’s not marked as volatile, then when
00:05:01.160
that changes becomes visible to other threads
00:05:03.740
depends on what locks were held,
00:05:05.951
and when the threads were created and
00:05:08.531
destroyed.
00:05:09.000
There are three different cases.
00:05:12.000
Firstly, if a thread changes the value
00:05:14.971
of a non-volatile field, while holding a
00:05:17.941
lock, then releases that lock, and then
00:05:20.912
some other thread acquires the lock,
00:05:23.459
then the thread that acquires the lock
00:05:26.429
is guaranteed to see the written value.
00:05:29.500
Secondly, if a new thread is created,
00:05:31.848
it sees the state of the system
00:05:34.197
as if it had just acquired a
00:05:36.545
lock that had just been released by
00:05:38.894
the creating thread.
00:05:40.000
And, thirdly, if a thread terminates,
00:05:42.587
then the changes it made become visible
00:05:45.606
to other threads.
00:05:47.000
Outside of these three cases however,
00:05:50.240
there are no guarantees.
00:05:52.500
If two threads concurrently access a variable
00:05:55.057
without proper locking, then the changes made
00:05:57.613
by one thread might be visible to
00:06:00.170
the other.
00:06:01.000
Or they might not.
00:06:03.500
It depends on hardware, and on the
00:06:06.440
exact details of the thread scheduling,
00:06:08.960
and it isn’t predictable to the programmer.
00:06:12.000
The only other guarantee made is that
00:06:14.674
accesses to 32-bit fields, such as integer
00:06:17.349
and floating point values, is atomic.
00:06:19.641
The system will never observe a half-completed
00:06:22.315
write to an int or a float,
00:06:24.990
even if it’s incorrectly synchronised.
00:06:27.000
But this guarantee doesn’t hold for 64-bit
00:06:30.225
fields, such as long or double values,
00:06:33.450
where corrupted and half-written, values can be
00:06:36.675
observed if the system isn’t correctly locked.
00:06:40.000
This memory model allows flexibility for the
00:06:43.413
hardware.
00:06:44.000
It allows that each processor core can
00:06:46.630
see a different view of the memory,
00:06:49.259
and that the views of the memory
00:06:51.889
can diverge between different threads. And only
00:06:54.519
the explicit use of locks requires synchronisation
00:06:57.149
between cores.
00:06:58.000
This lets us write portable code,
00:07:00.800
if we pay attention to locking concurrent
00:07:04.067
accesses, whilst allowing good performance.
00:07:09.000
It’s increasingly clear that all languages need
00:07:12.442
to define their memory model.
00:07:15.000
If the language definition isn’t explicit about
00:07:17.800
when concurrent accesses become visible, it runs
00:07:20.600
the risk that different processors will behave
00:07:23.400
differently, and these differences will be visible
00:07:26.200
to the programmer.
00:07:27.500
So, to have any hope of correctness,
00:07:29.740
the language has to be clear what
00:07:31.980
behaviour the programmer can rely on.
00:07:34.000
Unfortunately, Java is unusual in having such
00:07:38.391
a clearly-specified memory model.
00:07:41.000
C and C++ have historically had very
00:07:44.180
poorly specified memory models. The recent versions
00:07:47.361
of both standards have now fixed this,
00:07:50.541
leaning very heavily on the work done
00:07:53.722
for Java, but it’s taking a long
00:07:56.902
time for compilers to implement those standards,
00:08:00.083
and to become available.
00:08:02.000
And Rust also does not yet have
00:08:04.679
a fully specified memory model, although one
00:08:07.358
is under development. Specifying a memory model
00:08:10.037
for Rust is complicated compared to C
00:08:12.715
or C++ or Java, because Rust has
00:08:15.394
several different reference types and ownership rules,
00:08:18.073
and because of the distinction between safe
00:08:20.752
and unsafe code.
00:08:22.000
This is one of the current limitations
00:08:24.256
of Rust.
00:08:28.000
As we’ve seen, the memory model of
00:08:30.514
a language is explicitly tied into the
00:08:33.027
way it manages locking and communication between
00:08:35.541
threads.
00:08:36.000
Most operating systems expose concurrency to applications
00:08:39.115
in the form of multiple processes,
00:08:41.785
each potentially containing multiple threads of execution.
00:08:45.000
And processes are isolated from each other,
00:08:48.118
and don’t share memory.
00:08:50.000
Threads within a process, though, share access
00:08:52.772
to a common pool of memory,
00:08:55.148
and make use of synchronisation to manage
00:08:57.920
access to that shared memory.
00:09:00.000
They require explicit locks around critical sections
00:09:03.442
where shared resources are accessed.
00:09:06.000
How this is done depends on the
00:09:09.485
language. In Java, for example, the locks
00:09:12.970
are provided by the implementation of synchronised
00:09:16.454
methods and synchronised blocks. In C,
00:09:19.441
they’re provided by the pthreads library,
00:09:22.428
in the form of pthread_mutex_lock() and pthread_mutex_unlock(),
00:09:25.913
in C++ by the std::thread class.
00:09:29.000
And these provide the synchronisation primitives,
00:09:31.495
and ensure access to shared data follows
00:09:34.405
the memory model of the language.
00:09:37.000
And, outside of such protected, such locked,
00:09:39.542
regions, there are very few guarantees about
00:09:42.084
concurrent accesses to shared memory.
00:09:47.000
The approach of providing multiple threads,
00:09:49.633
and using locks to protect access to
00:09:52.706
shared memory, is extremely common.
00:09:55.000
But it’s also really problematic.
00:09:58.000
It’s proven difficult to define a memory
00:10:00.596
model for a languages that provides good
00:10:03.192
performance, whilst also allowing programmers to reason
00:10:05.787
about the code.
00:10:07.000
It’s difficult to know when the locking
00:10:10.056
is done correctly. Failures are silent.
00:10:12.676
Incorrectly locked code tends to compile just
00:10:15.732
fine, but errors tend to manifest themselves
00:10:18.788
under heavy load. This make such code
00:10:21.844
hard to write, and hard to debug.
00:10:25.000
Balancing performance and correctness is difficult.
00:10:27.668
It’s easy to over- or under-lock programs.
00:10:30.781
To add too many, or too few
00:10:33.894
locks. And if you lock too much,
00:10:37.006
or for too long, then the performance
00:10:40.119
is bad. But lock too little,
00:10:42.787
and the code occasionally and unpredictably fails.
00:10:46.000
It’s difficult to enforce correct locking,
00:10:48.262
and difficult to guarantee freedom from deadlocks.
00:10:53.000
And it’s difficult to compose code that
00:10:56.033
uses locks.
00:10:57.000
And this, I think, is the real
00:11:00.715
argument against locks as synchronisation mechanism.
00:11:04.000
In principle, at least, it’s possible to
00:11:06.948
write small-scale code correctly using locks to
00:11:09.897
control access to shared data. It’s not
00:11:12.845
easy, and most people get it wrong,
00:11:15.794
but in principle it’s possible.
00:11:18.000
The problem is, though, is that lock-based
00:11:21.080
code doesn’t compose.
00:11:22.500
If you have two functions that each
00:11:25.790
use locking correctly, then the result of
00:11:29.080
combining them may not be correct.
00:11:32.000
The example everyone uses to illustrate this
00:11:35.118
is a banking system.
00:11:37.000
Assume you have a bank account class,
00:11:39.545
that correctly uses locks to protect access
00:11:42.089
to the account. You want to write
00:11:44.634
a program to transfer money between two
00:11:47.178
accounts. And that program shouldn’t expose the
00:11:49.723
intermediate state. That is, the money should
00:11:52.268
either be in account A, or it
00:11:54.812
should be in account B, but it
00:11:57.357
shouldn’t be possible to see a situation
00:11:59.901
where the money is in both accounts,
00:12:02.446
or in neither account.
00:12:04.000
Unfortunately, the locking on the individual accounts
00:12:06.983
doesn’t protect this. Even if the accounts
00:12:09.967
are correctly locked, it’s still possible for
00:12:12.950
another thread to observe the intermediate state
00:12:15.933
where, the money is gone from one
00:12:18.917
account but not arrived in the other.
00:12:22.000
The individual operations are correct, but the
00:12:25.150
combined operation is not. We need to
00:12:28.300
add extra locks to make the combination
00:12:31.450
correct.
00:12:32.000
And this is fundamental to the way
00:12:34.596
locks work. It cannot be fixed by
00:12:37.192
careful coding. It’s a limit of the
00:12:39.787
locking abstraction itself.
00:12:43.000
And for these reasons, it’s time we
00:12:46.177
thought again about alternative concurrency models.
00:12:49.000
Multicore systems are now ubiquitous. Concurrency is
00:12:54.163
everywhere.
00:12:55.000
But multithreaded code with shared access protected
00:12:58.355
by locking is incredibly hard to write
00:13:01.710
correctly. And even when written correctly,
00:13:04.586
is prone to failures when combined into
00:13:07.941
complete systems.
00:13:09.000
In the following parts, I’ll talk about
00:13:12.019
two alternatives to lock-based concurrency: transactions and
00:13:15.037
message passing.
00:13:19.000
So that’s all for this part.
00:13:20.980
I’ve spoken about the need for languages
00:13:23.290
to have a well-defined memory model.
00:13:25.270
And about some of the limitations of
00:13:27.580
lock-based concurrency and multi-threading.
00:13:29.000
In the next part, I’ll talk about
00:13:31.917
transactions as a concurrency model.
Part 2: Managing Concurrency Using Transactions
The second part of this lecture discusses the atomic transactions
as an alternative concurrent programming model. It reviews the ACID
properties of transactions, and introduces the transactions programming
model and its consequences and benefits. It discusses how this style
of programming is a good fit for Haskell, and the monadic programming
style, any why it's not a good fit for more mainstream programming
languages.
00:00:00.000
In this part, I’d like discuss an
00:00:03.174
alternative approach to managing concurrency, based on
00:00:05.347
the idea of atomic transactions.
00:00:07.000
I’ll talk about the transactional programming model,
00:00:09.596
the benefits it claims to offer,
00:00:11.821
and some of the implications of adopting
00:00:14.417
that approach to concurrency.
00:00:16.000
And I’ll discuss how transactions integrate with
00:00:18.471
Haskell, and how they fit into more
00:00:20.941
mainstream programming languages.
00:00:24.000
The goal of atomic transactions is to
00:00:26.687
provide an alternative way of managing concurrency,
00:00:29.374
that avoids the problems inherent in the
00:00:32.061
use of multithreading with shared mutable state
00:00:34.748
managed by locks.
00:00:36.000
The fundamental idea is to structure a
00:00:39.150
program as a sequence of atomic transactions,
00:00:42.300
where transactions in different threads can proceed
00:00:45.450
concurrently.
00:00:46.000
Each transaction wraps some computation, such that
00:00:48.826
it either succeeds or it fails in
00:00:51.652
its entirety, and so that intermediate states
00:00:54.478
are not visible to other threads
00:00:57.000
The execution of the transactions is managed
00:01:00.013
by a runtime, and the runtime ensures
00:01:03.026
that the transactions obey the usual four
00:01:06.039
ACID properties.
00:01:07.000
Firstly, that each transaction is atomic.
00:01:09.446
That is, it succeeds or fails in
00:01:12.300
its entirety, and any intermediate states are
00:01:15.154
not visible to other threads. All of
00:01:18.008
the actions in a transaction are performed,
00:01:20.862
or none of them are.
00:01:23.000
Secondly, that transactions are consistent. The runtime
00:01:25.724
ensures that the data in the system
00:01:28.448
is in a consistent state when the
00:01:31.172
transaction starts, is left in a consistent
00:01:33.896
state when it ends, and at no
00:01:36.620
point are inconsistent values visible to the
00:01:39.343
rest of the system.
00:01:41.000
If the transaction succeeds, that consistent state
00:01:44.010
reflects the completed action. If it fails,
00:01:47.020
the effects are cleanly rolled back,
00:01:49.600
and the state is as-if the transaction
00:01:52.610
was never attempted.
00:01:54.000
Third, transactions are isolated. The execution of
00:01:57.170
a transaction will, of course, comprise a
00:02:00.340
number of steps, a number of intermediate
00:02:03.509
states. The runtime ensures that none of
00:02:06.679
those intermediate states are visible outside of
00:02:09.849
the transaction. To the rest of the
00:02:13.019
program, the transaction proceeds indivisibly and completely,
00:02:16.189
or not at all.
00:02:18.000
And, finally, transactions are durable. A transaction
00:02:21.113
may succeed, or it may fail and
00:02:24.226
be rolled back. But, if it succeeds
00:02:27.339
and commits its result, then that result
00:02:30.453
will persist. A successful transaction will never
00:02:33.566
be rolled back.
00:02:35.000
These, properties, known as the ACID properties,
00:02:38.647
are probably familiar to you, since they
00:02:42.295
frequently apply to database systems.
00:02:45.000
Why might it make sense to structure
00:02:47.275
a program in this way?
00:02:49.000
Because transactions structured in this way can
00:02:53.254
be composed arbitrarily, without affecting correctness.
00:02:57.000
As we saw in the previous part,
00:02:59.948
with the example of the bank account
00:03:02.897
class, how two correctly locked bank account
00:03:05.845
objects, when combined, could produce a system
00:03:08.794
that exposed the internal state.
00:03:11.000
And this problem doesn’t occur with transactions.
00:03:13.765
No matter how they are composed,
00:03:16.135
it doesn’t affect correctness of the code.
00:03:19.000
And transactions also avoid deadlocks that can
00:03:21.423
occur due to acquiring locks in the
00:03:23.846
wrong order, since there are no locks.
00:03:26.269
And they avoid race conditions.
00:03:31.000
The programming model for systems using transactions
00:03:34.430
is straight forward.
00:03:36.000
Blocks of code are labelled as atomic.
00:03:39.000
And the runtime executes those code blocks,
00:03:41.826
ensuring that execution respects the ACID properties,
00:03:44.652
and allows atomic blocks to run concurrently
00:03:47.478
with respect to other atomic blocks.
00:03:50.000
And the programmer doesn’t have to worry
00:03:52.683
about locking or synchronisation. The runtime takes
00:03:55.367
care of all that.
00:03:57.000
This is implemented using optimistic transactions.
00:04:02.000
When an atomic block is entered,
00:04:04.353
the runtime starts to maintain a thread
00:04:07.097
local transaction log. This transaction log maintains
00:04:09.842
a record of every memory read or
00:04:12.587
write, and every potential I/O operation,
00:04:14.939
made by the atomic block.
00:04:17.000
When the block completes, the transaction log
00:04:19.542
is validation, to check that it saw
00:04:22.084
a consistent view of memory.
00:04:24.000
If the validation succeeds, then the atomic
00:04:27.220
block, the transaction, commits its changes to
00:04:30.440
memory.
00:04:31.000
If not, if this transaction was competing
00:04:35.134
with another transaction and lost out,
00:04:38.678
then the atomic block, the transaction,
00:04:42.222
is rolled block to the beginning,
00:04:45.766
undoing any changes, and retried from scratch.
00:04:50.000
The assumption, of course, is that conflicts
00:04:52.596
between transaction are rare, and that most
00:04:55.192
atomic blocks complete and commit their results
00:04:57.788
the first time.
00:04:59.000
And if that’s not the case,
00:05:01.357
if there are many conflicting transactions,
00:05:03.714
then progress will be slow, due to
00:05:06.464
repeated rollbacks, but the transactions will eventually
00:05:09.214
make progress.
00:05:12.000
Now, as we’ve seen, the runtime will
00:05:15.041
roll-back and retry transactions, if their transaction
00:05:18.081
log fails to validate because they lose
00:05:21.122
out in competition to one of the
00:05:24.162
other transactions proceeding concurrently.
00:05:26.000
A consequence of this, is that it
00:05:28.822
needs to be possible to roll-back and
00:05:31.644
retry a transaction. And to make this
00:05:34.466
possible, the runtime has to place some
00:05:37.287
restrictions on transaction behaviour.
00:05:39.000
The key restriction is that a transaction
00:05:41.819
needs to be referentially transparent. That is,
00:05:44.638
the result returned by a transaction must
00:05:47.457
depend solely on its inputs, and it
00:05:50.276
must generate the same result each time
00:05:53.095
it executes.
00:05:54.000
And it must not perform I/O operations
00:05:57.456
during the transaction. It must not do
00:06:00.913
anything irrevocable.
00:06:02.000
The code sample on the slide is
00:06:05.150
problematic, for example, because a concurrent transaction
00:06:08.300
might modify the values of n or
00:06:11.450
k.
00:06:12.000
Now, this would be detected when the
00:06:14.373
transaction log is validated, at the end
00:06:16.746
of the atomic block, when it’s time
00:06:19.120
to commit or rollback the transaction.
00:06:21.154
But that might be too late to
00:06:23.527
stop the missiles being launched by accident.
00:06:26.000
So the runtime system has to enforce
00:06:28.800
these restrictions, else we’ve just traded hard
00:06:31.600
to find locking bugs, for hard to
00:06:34.400
find transaction consistency bugs.
00:06:38.000
So, what we see is that unrestricted
00:06:42.391
I/O breaks transaction isolation.
00:06:45.000
If a transaction can read or write
00:06:47.319
files, if it can send or receive
00:06:49.638
data over the network, if it can
00:06:51.956
take input from the mouse or keyboard,
00:06:54.275
update the display, play or record sound,
00:06:56.594
etc., then the progress of the transaction
00:06:58.913
can be observed before it commits.
00:07:01.000
This breaks the ACID properties. It breaks
00:07:04.413
isolation.
00:07:05.000
And it makes it impossible to roll-back
00:07:08.811
the transaction.
00:07:10.000
To address this, the language and runtime
00:07:13.450
need to control when I/O is performed.
00:07:17.000
They need to remove the global functions
00:07:19.975
that allow unrestricted I/O from the standard
00:07:22.950
library, instead replace them with versions that
00:07:25.925
allow control over when I/O can occur.
00:07:29.000
One way this could work is if
00:07:31.530
the system provided an I/O context object,
00:07:34.059
that was passed as a parameter to
00:07:36.589
main(). This object would have methods that
00:07:39.118
allow reading and writing to files,
00:07:41.286
access to standard input and standard output,
00:07:43.816
and so on.
00:07:45.000
And functions such as printf() would become
00:07:48.177
methods on the I/O context object.
00:07:51.000
And if a function needs to perform
00:07:53.665
I/O, then it would need to be
00:07:56.331
passed this I/O content object, so it
00:07:58.996
could invoke the appropriate methods.
00:08:01.000
This would allow control over what functions
00:08:03.608
can perform I/O. If you want to
00:08:06.215
prevent a transaction from writing to a
00:08:08.823
file, for example, don’t pass it the
00:08:11.430
I/O context object, and it can’t read
00:08:14.038
or write to any files.
00:08:16.000
Now, this is not how I/O works
00:08:19.193
in Rust, or in C, or in
00:08:22.386
Java, or in any other mainstream languages,
00:08:25.579
although arguably it maybe should be.
00:08:28.316
But it is how I/O works in
00:08:31.509
Haskell. The I/O context object I’m describing
00:08:34.702
is essentially the I/O monad, and Haskell
00:08:37.895
shows that this approach to controlling I/O
00:08:41.088
can work.
00:08:45.000
In addition to controlling I/O operations,
00:08:48.646
atomic transactions require control over side effects.
00:08:53.000
Functions that are referentially transparent, that only
00:08:55.956
depend on their arguments and that don’t
00:08:58.911
depend on access to shared state,
00:09:01.444
to shared memory, can be accessed normally.
00:09:04.500
But, if a function accesses memory that
00:09:06.847
might be shared with other functions,
00:09:08.859
if it manipulates a value on the
00:09:11.206
heap that might be shared with other
00:09:13.553
transactions, then that access must be controlled.
00:09:16.000
Functions within a transaction can perform memory
00:09:19.025
accesses, but the runtime must track those
00:09:22.049
accesses. The runtime must track memory reads
00:09:25.074
and writes during a transaction, so it
00:09:28.098
can validate that there are no conflicts
00:09:31.123
with other ongoing transactions, and so that
00:09:34.147
it can roll-back any changes, if necessary,
00:09:37.172
if such conflicts occur.
00:09:39.000
And this can be done in software,
00:09:41.625
by the language runtime, by wrapping memory
00:09:44.250
access in some kind of smart pointer
00:09:46.875
object. And this approach is known as
00:09:49.500
software transactional memory, STM.
00:09:51.000
Alternatively, some processors provide hardware support to
00:09:56.027
accelerate such pointer tracking.
00:09:59.000
The principle is similar to that for
00:10:02.019
controlling I/O. Disallow unrestricted heap access,
00:10:04.607
in the same way unrestricted file access
00:10:07.627
way disallowed, and provide a memory transaction
00:10:10.646
context. And require this transaction context to
00:10:13.666
be passed to atomic blocks if they
00:10:16.685
are to access memory, to allow them
00:10:19.704
to perform only checked memory access,
00:10:22.293
and to provide the abilIty to validate
00:10:25.312
and rollback memory accesses if necessary.
00:10:28.000
And, again, this is not, perhaps,
00:10:30.824
mainstream, but it’s familiar to Haskell programmers
00:10:34.118
as the state monad.
00:10:39.000
So, we’ve seen that Haskell limits the
00:10:41.765
ability of a function to perform I/O,
00:10:44.530
or access memory by using monads.
00:10:47.000
Monads are one of the less well
00:10:50.755
understood parts of Haskell.
00:10:53.000
The way I think of them,
00:10:55.219
as someone who’s not a Haskell programmer,
00:10:57.807
is that Haskell defines a set of
00:11:00.395
actions that can be performed in a
00:11:02.984
certain context, along with some rules,
00:11:05.202
a monad, for chaining together those actions
00:11:07.791
in that context.
00:11:09.000
The putChar function, for example, as we
00:11:11.665
see on the slide, takes a character
00:11:14.331
and returns an action that writes the
00:11:16.996
character to the I/O context.
00:11:19.000
The getChar function returns an action that
00:11:22.253
retrieves a character from the I/O context.
00:11:25.506
And so on.
00:11:27.000
The main function holds the I/O context,
00:11:29.544
and functions that need to read or
00:11:32.088
write to files are tagged as operating
00:11:34.632
in that context. And if a function
00:11:37.176
is not tagged in this way,
00:11:39.356
it can’t read or write to files.
00:11:42.000
And this gives us the ability to
00:11:45.442
restrict I/O during atomic transactions.
00:11:48.000
We make sure the definition of the
00:11:50.683
atomic block isn’t tagged as being part
00:11:53.367
of the I/O context.
00:11:55.000
This gives a way of preventing atomic
00:11:58.182
transactions from reading or writing files.
00:12:00.909
It’s wrapped in complex type-theoretic abstractions,
00:12:03.636
because Haskell, but essentially it’s just restricting
00:12:06.818
access to the functions that perform I/O.
00:12:13.000
That works for controlling I/O, but how
00:12:15.858
to control access to memory?
00:12:18.000
Well, Haskell uses a similar approach.
00:12:23.000
The state monad is used to define
00:12:26.715
an STM, software transactional memory, context.
00:12:30.000
The function, newTVar, defines a transactional variable,
00:12:33.052
that exists within such a context.
00:12:35.668
This holds a reference to a potentially
00:12:38.720
shared value on the heap.
00:12:41.000
And the readTVar and writeTVar functions return
00:12:44.398
actions that allow reading and writing to
00:12:47.795
that shared value within an STM context,
00:12:51.193
but that coordinate with the runtime and
00:12:54.590
atomic transaction implementation, to track conflicting access
00:12:57.988
to such values between different transactions.
00:13:01.000
And the implementation of an atomic block
00:13:03.827
provides an STM context that allows the
00:13:06.654
transactional variables to be used within a
00:13:09.481
transaction, but prohibits their use outside that
00:13:12.308
context. And, as we see from the
00:13:15.135
slide, the atomic block returns an I/O
00:13:17.962
context that actually reads and write the
00:13:20.788
values to memory.
00:13:25.000
Transactional memory is a good fit with
00:13:28.500
Haskell.
00:13:29.000
And the reason it works is that
00:13:31.832
Haskell provides the necessary type system features
00:13:34.664
to control I/O and control other side
00:13:37.495
effects.
00:13:38.000
The use of pure functions, lazy evaluation,
00:13:41.990
and monads, all ensure that the transaction
00:13:45.980
semantics, the ACID properties, are preserved.
00:13:49.500
The STM context, and the use of
00:13:52.850
transactional variables, constrains and limits access to
00:13:56.200
memory, and tracks side effects, allowing conflicting
00:13:59.550
transactions to be detected and rolled back.
00:14:03.000
And the definition of the atomic block,
00:14:06.085
that ensures the transaction is not in
00:14:09.170
the IO context, prevents reading or writing
00:14:12.256
to files, or otherwise performing I/O.
00:14:15.000
The result is clean and elegant.
00:14:17.545
It’s a nice abstraction for concurrency.
00:14:20.091
It allows composition of functions without worrying
00:14:23.061
about locking. It can’t deadlock. And it’s
00:14:26.030
easy to reason about, easy to use.
00:14:32.000
If you’re a Haskell programmer, atomic transactions
00:14:36.130
are very powerful.
00:14:38.000
But they rely on features of the
00:14:40.967
type system that are not commonly or
00:14:43.933
widely understood, in order to provide safety.
00:14:47.000
Integrating atomic transactions into more mainstream languages
00:14:51.830
is not straightforward.
00:14:54.000
Most languages can’t enforce the use of
00:14:57.114
pure functions, or referential transparency. Most languages
00:15:00.228
can’t limit the use of I/O,
00:15:02.897
and can’t track memory accesses to avoid
00:15:06.010
side effects.
00:15:07.000
Atomic transactions can be used without these
00:15:10.206
restrictions, of course, but doing so requires
00:15:13.412
the programmer to have discipline to ensure
00:15:16.618
correctness. The programmer has to avoid side
00:15:19.824
effects, and avoid I/O, without help from
00:15:23.030
the compiler. And if the programmer does
00:15:26.236
this incorrectly, difficult to find bugs get
00:15:29.442
introduced.
00:15:30.000
And this is the risk. Atomic transactions
00:15:32.929
are only safe if the language and
00:15:35.858
the runtime can control I/O and control
00:15:38.787
side effects. And the only language that
00:15:41.716
has the necessary mechanisms to do that
00:15:44.645
safely, is Haskell.
00:15:46.000
It’s not clear that the transactional approach
00:15:48.545
generalises to other languages.
00:15:54.000
Atomic transactions are an interesting idea.
00:15:59.000
In Haskell, they offer a compelling experience.
00:16:02.197
They avoid problems due to race conditions,
00:16:05.395
locking, and deadlocks in concurrent code.
00:16:08.135
And they allow arbitrary composition of functions
00:16:11.332
without having to worry whether the result
00:16:14.530
is correctly locked.
00:16:16.000
In other languages, though, the benefits are
00:16:20.130
less clear cut.
00:16:22.000
And what’s not clear to me,
00:16:23.595
is whether this is an example of
00:16:25.456
Haskell doing the right thing, and the
00:16:27.317
rest of the world just needs to
00:16:29.178
learn to program in a pure functional
00:16:31.039
style if we want safe concurrent code.
00:16:33.000
Or if Haskell has developed an approach
00:16:36.465
that’s interesting in theory, but that will
00:16:39.930
be forever impractical in mainstream languages.
00:16:43.000
The paper linked from the slide talks
00:16:45.250
about atomic transactions and how they work
00:16:47.500
in detail. I encourage you to read
00:16:49.750
it, and to think about the ideas.
00:16:54.000
And that concludes our discussion of atomic
00:16:57.259
transactions. I’ve outlined the programming model,
00:17:00.053
how transactions can be integrated into Haskell,
00:17:03.312
and some of the difficulties in integrating
00:17:06.572
them into more mainstream languages.
00:17:09.000
In the next part, I’ll move on
00:17:12.333
to discuss another alternative concurrency mechanism,
00:17:15.190
that more friendly to mainstream languages:
00:17:18.048
message passing.
Part 3: Message Passing Systems
The third part of the lecture moves on from transactions, to discuss
message passing as a concurrency model. It introduces actor-based
programming, and the various styles of message passing system, using
examples in Scala + Akka and Rust. It shows how message passing can
provide a natural model for concurrent programming, that's familiar
for those with experience writing networked applications, but discusses
the limited guarantees provided compared to transactions.
00:00:00.470
In the previous part I spoke about
00:00:03.151
transactions as an alternative concurrency mechanism,
00:00:05.449
and we discussed how they're a good
00:00:08.131
fit for languages such as Haskell,
00:00:10.429
but perhaps not so well suited for
00:00:13.110
more mainstream languages.
00:00:14.359
In this part I want to move
00:00:17.086
on and talk about message passing systems
00:00:19.814
as another alternative to shared state concurrency
00:00:22.541
using multi-threading.
00:00:23.420
I’ll talk a bit about the concept
00:00:25.736
of actor-based systems and message passing,
00:00:27.721
about how communications is structured in these
00:00:30.036
systems. And I’ll give some examples of
00:00:32.352
how it's used in languages like Scala
00:00:34.668
and in Rust.
00:00:38.810
So what is a message passing system?
00:00:41.930
Well, the goal of a message passing
00:00:44.373
system is that the system gets structured
00:00:46.816
as a set of communicating processes.
00:00:49.010
These tends to be known as actors,
00:00:51.699
and they're structured such that they shared
00:00:54.388
no mutable state.
00:00:55.640
The actors communicate by sending messages to
00:00:58.338
each other. And the act of sending
00:01:01.036
a message is the only way communication
00:01:03.734
can occur in these systems. There's no
00:01:06.432
shared memory, there's no shared mutable state.
00:01:09.230
The messages in such systems are generally
00:01:12.166
required to be immutable, they can't change
00:01:15.102
after they've been sent.
00:01:16.880
The data is conceptually copied between processes
00:01:19.614
in these systems, although in practice it’s
00:01:22.348
implemented by copying a reference. But,
00:01:24.691
since the data is immutable, this has
00:01:27.425
no practical difference; you're exchanging messages that
00:01:30.159
can’t change.
00:01:31.040
Alternatively, some systems using a technique known
00:01:34.372
as linear types, essentially ownership tracking,
00:01:37.227
to ensure that messages are not referenced
00:01:40.559
after they've been sent. This allows mutable
00:01:43.890
data to be safely transferred.
00:01:46.370
The way this is implemented, if you
00:01:49.345
have a single system with shared memory,
00:01:52.320
is using threads and locks. You're passing
00:01:55.295
a reference to the message between threads.
00:01:58.370
And this obviously relies on the communication
00:02:01.669
mechanism being implemented correctly, and being correctly
00:02:04.969
locked.
00:02:05.540
The benefit, I think, comes because that
00:02:08.023
only has to be done once.
00:02:10.151
You have to implement the locks to
00:02:12.634
exchange messages once, as part of the
00:02:15.116
system, but then every system which is
00:02:17.599
built on top of that gets the
00:02:20.082
correctly locked communication mechanism for free.
00:02:22.310
And these systems have the advantage,
00:02:24.554
of course, that they’re trivial to distribute.
00:02:27.172
Since you're passing messages between systems,
00:02:29.416
and those messages are either immutable,
00:02:31.760
or the runtime, the type system,
00:02:34.416
ensures that ownership is tracked and enforces
00:02:37.515
that they’re sent, it becomes possible to
00:02:40.614
make a distributed system very easily
00:02:43.370
just by sending the messages down a
00:02:46.072
socket to another node on the network,
00:02:48.774
rather than passing them by shared memory
00:02:51.476
within a single system.
00:02:53.120
So the runtime obviously needs to be
00:02:55.078
aware that it's distributed, but it's possible
00:02:57.036
to build these applications, such that they
00:02:58.995
can run across multiple nodes on the
00:03:00.953
network, and such that the application is
00:03:02.911
unaware that they are distributed.
00:03:07.550
The implementation of one of these,
00:03:10.222
if you look at how an actor
00:03:13.339
is implemented,
00:03:14.330
tends to have a queue of messages
00:03:17.524
which have arrived and are waiting to
00:03:20.717
be processed. The queue is where synchronisation
00:03:23.911
happens; there's a lock on the queue
00:03:27.105
data structure and processes,
00:03:29.030
other actors, which are sending messages,
00:03:31.575
get a lock on the queue and
00:03:34.545
append their messages to the queue.
00:03:37.190
The message at the head of the
00:03:39.729
queue is de-queued. It goes to a
00:03:42.267
dispatcher, which then looks at the type
00:03:44.806
of the message and pattern matches against
00:03:47.345
the type.
00:03:48.170
And the receiving process then executes a
00:03:50.569
different action depending on what type of
00:03:52.969
message has been received.
00:03:54.440
And when that's done, it just loops
00:03:56.762
around and pulls the next message off
00:03:59.085
the queue, and just executes in a
00:04:01.407
loop, processing message, after message, after message.
00:04:03.830
If it needs to communicate with the
00:04:06.080
other actors in the system, it can
00:04:08.329
send messages out, and they get queued
00:04:10.579
up to be processed by the other
00:04:12.829
actors.
00:04:13.250
The entire system, then, proceeds as a
00:04:16.168
set of actors, each processing messages in
00:04:19.085
a loop, sending messages out to other
00:04:22.003
actors.
00:04:22.520
It looks a lot like a networked
00:04:24.530
system; a lot like a networked server.
00:04:26.540
It processes messages and it sends replies.
00:04:32.120
There are lots of different ways in
00:04:34.570
which you can structure these systems.
00:04:36.770
It’s possible to build actor-based message passing
00:04:40.007
systems that operate in a synchronous or
00:04:43.243
an asynchronous manner; it’s possible to make
00:04:46.480
them statically or dynamically typed; or that
00:04:49.716
they deliver messages directly to actors,
00:04:52.491
or indirectly via channels.
00:04:54.440
And each of these different approaches has
00:04:56.720
its own advantages and its own disadvantages.
00:05:04.280
It’s possible for the communication be synchronous
00:05:08.706
or asynchronous.
00:05:10.070
It’s possible that message passing involves a
00:05:13.146
rendezvous between the sender and the receiver.
00:05:16.222
A synchronous message exchange.
00:05:18.080
In this case, the sender waits for
00:05:20.733
the receiver to become available when the
00:05:23.386
message is sent. Or, if the receiver
00:05:26.040
gets to the rendezvous first, it waits
00:05:28.693
for the sender.
00:05:29.930
And this has the benefit of making
00:05:33.459
the two time-aligned. You know that both
00:05:36.987
are available, both sender and receiver are
00:05:40.516
available, at the point of communication.
00:05:43.640
Alternatively, the communication can be asynchronous.
00:05:46.239
The sender can send a message and
00:05:49.271
continue, without waiting for the receiver to
00:05:52.304
receive it.
00:05:53.270
In this case, the message is buffered
00:05:56.324
up somewhere, and eventually gets delivered to
00:05:59.378
the receiver.
00:06:00.350
And, in some ways, that's advantageous because
00:06:03.191
the sender can keep doing some other
00:06:06.032
work while waiting for the receiver to
00:06:08.872
process the message.
00:06:10.190
But it has the risk that the
00:06:12.953
receiver has somehow failed, and is not
00:06:15.717
processing messages, or it's not processing messages
00:06:18.480
quickly enough.
00:06:19.370
You can get a backlog of messages
00:06:22.317
building up. And to some extent that
00:06:25.265
can be problematic. You don't want the
00:06:28.212
sender to keep putting messages into the
00:06:31.160
queue if the receiver isn't processing them.
00:06:34.107
It wants to somehow be aware of
00:06:37.055
the failure, of the delays.
00:06:39.260
And these systems can get unbalanced.
00:06:43.640
There's no back-pressure to gradually slow the
00:06:46.835
system down, if one part of it
00:06:50.031
isn't keeping up.
00:06:51.500
So there are perhaps advantages to
00:06:54.680
systems where there’s a synchronous rendezvous,
00:06:56.961
or where there’s a limited amount of
00:06:59.623
buffering capacity and, beyond that, the rendezvous
00:07:02.285
become synchronous. Just to provide back-pressure,
00:07:04.566
to make sure the whole system is
00:07:07.228
operating at the speed of it’s slowest
00:07:09.890
component.
00:07:10.370
Of course, if you have an asynchronous
00:07:12.220
system, you can simulate a synchronous system
00:07:14.069
by waiting for a reply, so you
00:07:15.919
know the message was received.
00:07:21.350
Different systems also make different choices around
00:07:24.971
the typing of messages.
00:07:27.140
it’s possible to build statically typed systems,
00:07:30.047
where the types of the messages which
00:07:32.954
can be sent to a particular actor
00:07:35.861
are well defined and checked in the
00:07:38.768
type system, checked by the compiler.
00:07:41.360
In these types of systems, the compiler
00:07:44.429
checks that a receiver can handle all
00:07:47.498
the possible messages it can receive.
00:07:50.129
And the system won't compile if it
00:07:53.198
can't handle the different messages.
00:07:55.490
And, in some ways, this provides robustness.
00:07:58.007
A receiver is guaranteed to be able
00:08:00.523
to understand all the messages it receives.
00:08:03.140
Alternatively, the system can be more dynamically
00:08:06.380
typed, where the communication medium, the communication
00:08:09.619
channel, the message passing system, conveys the
00:08:12.859
type of the message
00:08:14.810
and the receiver pattern matches on those
00:08:17.075
types, and tries to figure out if
00:08:19.339
it can respond to the messages.
00:08:21.380
If the typing is very dynamic,
00:08:23.227
this has the potential for runtime failures,
00:08:25.381
of course. It's possible to send a
00:08:27.535
message to a receiver which it doesn't
00:08:29.689
understand. So these types of system tend
00:08:31.844
to have a catch-all in there,
00:08:33.690
and they tend to specify what the
00:08:35.844
receiver does
00:08:36.560
if it receives an unknown message type.
00:08:42.860
And these are perhaps more flexible.
00:08:45.560
You don't need to
00:08:48.050
evolve the system all at once.
00:08:50.288
And it's possible to build systems that
00:08:52.899
can optionally handle certain types of messages,
00:08:55.509
and just discard messages they don’t understand.
00:08:58.220
So this may potentially make a more
00:09:01.634
evolvable system. And, especially for distributed systems,
00:09:05.047
this potentially offers the flexibility to upgrade
00:09:08.461
the system in parts, and to evolve
00:09:11.875
the system.
00:09:12.950
But it does mean you have to
00:09:14.800
think about how to handle unknown messages,
00:09:16.650
and have the risk of runtime failures.
00:09:22.700
You also need to think about whether
00:09:25.336
messages are being sent directly between named
00:09:27.971
processes, whether messages being sent directly to
00:09:30.607
an actor,
00:09:31.460
or whether they're being sent indirectly via
00:09:35.359
some communications channel.
00:09:37.130
Some of these systems are arranged such
00:09:40.045
that they directly send messages to actors.
00:09:42.960
You get a reference to the actor,
00:09:45.875
and you can directly message that actor.
00:09:48.890
Others have this idea of channels,
00:09:51.523
where you get a reference to a
00:09:54.595
communications channel, and you put messages into
00:09:57.667
that channel. And the receiver takes them
00:10:00.739
out of the channel, out of the
00:10:03.811
communications link, and puts them into its
00:10:06.883
mailbox for processing.
00:10:08.300
The use of explicit channels
00:10:11.750
adds overhead in some ways. It requires
00:10:14.536
you to explicitly plumb the system together,
00:10:17.322
and connect up the communications channels to
00:10:20.108
the senders and receivers.
00:10:21.800
But, it provides an extra level of
00:10:24.442
indirection.
00:10:24.920
And this can potentially be useful for
00:10:27.520
evolving the system, in that you can
00:10:30.120
change the receiver without the senders having
00:10:32.721
to know that the receiver has changed.
00:10:35.321
Or, similarly, you can change the senders
00:10:37.921
without the receiver having to know.
00:10:40.250
And, as long as the communications link
00:10:42.637
is there, you can change what's connected
00:10:45.024
to the endpoints. And that potentially is
00:10:47.411
useful to evolve the system. You don't
00:10:49.798
have to tell all the senders when
00:10:52.185
you change the receiving process.
00:10:53.990
And explicit channels are also perhaps a
00:10:56.759
natural place to define a communications protocol,
00:10:59.528
and to specify the types for messages
00:11:02.298
that can be transferred,
00:11:03.980
so they perhaps have an advantage that
00:11:06.422
way. Though, of course, the issue is
00:11:08.864
complexity, and having to plumb the system
00:11:11.307
together, so there’s some overhead too.
00:11:18.110
Actor-based systems are actually starting to see
00:11:22.387
fairly wide deployment.
00:11:24.320
And there's two different architectures that are
00:11:28.372
getting used.
00:11:29.630
The original architecture is that adopted by
00:11:32.942
the Erlang programming language, more recently by
00:11:36.254
Scala with the Akka library.
00:11:38.720
And these systems,
00:11:41.240
these systems are very dynamically typed.
00:11:44.420
You can send any type of message
00:11:46.590
to any receiver, and it pattern matches
00:11:48.760
on the type of messages and decides
00:11:50.930
whether it can handle them. And the
00:11:53.100
system has some sort of error handling
00:11:55.370
built in for what happens if it
00:11:57.709
gets a message it doesn't understand.
00:11:59.714
And maybe that kills the process,
00:12:01.718
maybe it ignores the message, or maybe
00:12:04.057
it drops into a custom error handling
00:12:06.396
routine.
00:12:06.830
So these systems are very dynamically typed.
00:12:09.117
They allow messages to be sent directly
00:12:11.405
to named actors, so you get an
00:12:13.692
actor reference and you send it a
00:12:15.980
message, rather than
00:12:17.060
sending messages via channels. And they both
00:12:21.297
provide transparent distribution of processes across the
00:12:25.535
network.
00:12:26.240
The alternative approach, which is starting to
00:12:29.626
see some interest, is a very statically-typed
00:12:33.011
approach, using explicit channels. This is what
00:12:36.397
we're seeing in the Rust programming language,
00:12:39.783
for example.
00:12:40.850
It’s asynchronous, it’s statically typed, and the
00:12:44.285
messages are sent into explicit channels,
00:12:47.230
and you have to explicitly plumb the
00:12:50.665
multiple threads together with the communication channels.
00:12:54.200
And they both work, they’re both seeing
00:12:56.498
use, but they’re quite different philosophies to
00:12:58.795
building actor-based systems.
00:13:03.980
So let's look at an example of
00:13:06.372
each of the two approaches.
00:13:08.180
So, the first one is an example
00:13:11.238
written in Scala programming language, using an
00:13:14.296
actor system known as Akka.
00:13:16.580
And Scala is a functional language,
00:13:19.400
which runs on the Java Virtual Machine.
00:13:22.790
And, what we see here, at the
00:13:25.225
bottom of the slide, we see the
00:13:27.661
main object being created. It says “object
00:13:30.096
Main extends App”. This is the main
00:13:32.531
object in the system, the equivalent of
00:13:34.966
the main function.
00:13:36.110
And this creates an actor runtime.
00:13:38.874
And then it creates an actor.
00:13:41.639
It says “val helloActor = runtime.actorOf”,
00:13:44.403
and this creates an actor of type
00:13:47.628
HelloActor, and it gives it a name,
00:13:50.853
and it assigns this to an immutable
00:13:54.079
variable helloActor.
00:13:55.100
And then it sends it some messages.
00:13:57.650
And the syntax with the actor name,
00:14:00.265
and the exclamation mark, and the message
00:14:02.880
is the syntax Akka uses to send
00:14:05.495
messages. And this sends the two messages
00:14:08.210
firstly “hello”, and then secondly “buenos dias”,
00:14:12.445
to the HelloActor.
00:14:14.360
And the code we see at the
00:14:17.364
top of the slide, the class HelloActor,
00:14:20.369
defines the entirety of the actor which
00:14:23.373
is receiving those messages.
00:14:25.190
It's got to receive method. The syntax
00:14:29.055
“def receive =” is defining a method.
00:14:33.020
And this method just pattern matches on
00:14:35.997
the types of messages it receives,
00:14:38.548
so it's like a match statement in
00:14:41.525
Rust.
00:14:42.050
it's got a case where, if it
00:14:44.715
receives the string “hello” it prints “hello
00:14:47.379
back at you”, and if it receives
00:14:50.044
any other type of message it just
00:14:52.709
says “huh?”.
00:14:53.570
And the actor just runs in a
00:14:56.234
loop. It just continually receives these messages
00:14:58.898
and processes them.
00:15:00.140
And it can pattern match in a
00:15:01.990
way that gets the message object,
00:15:03.577
which allows it to send a response
00:15:05.427
if it wants.
00:15:06.320
And it can store data in the
00:15:09.875
actor object, and that can include references
00:15:13.429
to other actors which it’s been sent,
00:15:16.984
and that allows it to build up
00:15:20.539
more complex communication patterns.
00:15:22.670
And everything’s very dynamic but it's quite
00:15:25.418
low
00:15:25.910
overhead, it’s quite syntactically clean.
00:15:32.750
We can also see, in this example,
00:15:35.610
how you might do it in Rust.
00:15:38.570
In this case, we have a main
00:15:41.417
function which creates a channel, spawns a
00:15:44.263
thread, and sends a message between them.
00:15:47.210
So let's walk through this.
00:15:49.340
To start with, we have a function,
00:15:51.851
main(),
00:15:52.310
and this holds the entire state of
00:15:54.844
the system, as is normal in Rust
00:15:57.378
programs.
00:15:59.570
The first thing that the main() function
00:16:02.382
does is create a channel.
00:16:04.490
The channel is defined in the standard
00:16:08.213
library, and is the inter-thread communication mechanism
00:16:11.936
for Rust.
00:16:13.100
And by calling the channel() call,
00:16:14.998
it returns you a tuple of the
00:16:17.212
transmitting and receiving ends of that channel.
00:16:19.426
The channels are unidirectional, and you transmit
00:16:21.641
into one end, and it comes out
00:16:23.855
of the receiving end.
00:16:25.220
And the main() function now has references
00:16:28.195
to both ends of channel.
00:16:34.010
We call thread::spawn(). This is the way
00:16:36.333
you create a new thread in Rust.
00:16:38.655
And, again, this comes from the standard
00:16:40.978
library, and the thread spawn() call creates
00:16:43.301
a new thread of execution.
00:16:48.170
What gets executed by that thread is
00:16:51.630
the contents of its argument. It's passed
00:16:55.089
what’s known as a closure. It's passed
00:16:58.549
a block of code, which captures the
00:17:02.009
necessary variables from its environment.
00:17:04.580
There’s two ways of writing an anonymous
00:17:06.798
closure like this, as we see in
00:17:09.016
the bottom of the slide.
00:17:10.700
You can just specify the arguments within
00:17:13.990
the bars, and then the code.
00:17:16.910
And, in that case, the closure borrows
00:17:19.612
its environment. It borrows the values of
00:17:22.314
its arguments, and any variables it references,
00:17:25.016
from the enclosing function.
00:17:26.660
Or you can define it by saying
00:17:29.115
“move”, followed by the arguments in bars,
00:17:31.569
followed by the code. And that takes
00:17:34.024
ownership of its arguments, it takes ownership
00:17:36.478
of the values it needs from the
00:17:38.933
environment. So it transfers ownership of the
00:17:41.387
data to the closure.
00:17:42.890
Now, in this particular case, we specify
00:17:46.306
a move closure,
00:17:47.870
so it's taking ownership. And there are
00:17:50.475
the two bars, with no arguments between
00:17:53.079
them, because this particular closure doesn't take
00:17:55.684
any explicit arguments.
00:17:56.900
And the body of the closure is
00:18:00.919
just code within the braces, where it
00:18:04.939
says “let _ = tx.send(42)”.
00:18:07.910
And you see this references the value
00:18:10.366
of tx, which was defined in the
00:18:12.822
main() function. So it's referenced a value
00:18:15.278
from its environment.
00:18:16.430
And, because it's a move closure,
00:18:18.920
it takes ownership of that. So the
00:18:21.825
ownership of the value tx has been
00:18:24.730
moved into this closure, and that's been
00:18:27.635
passed to the thread::spawn() call. So this
00:18:30.540
has moved the ownership of tx into
00:18:33.445
the other thread.
00:18:34.790
So, at this point, we have two
00:18:37.218
threads of execution running. We've got the
00:18:39.646
main thread, and we've got the new
00:18:42.074
thread which has been spawned. And the
00:18:44.502
thread which has been spawned has taken
00:18:46.930
ownership of the variable tx, so it's
00:18:49.358
got access to the transmit descriptor of
00:18:51.786
the channel.
00:18:52.580
But the receive descriptor still remains with
00:18:57.760
the main() function.
00:19:00.080
And it calls tx.send().
00:19:02.810
It transmits the number 42 down that
00:19:05.293
channel, and it assigns the return value
00:19:07.777
to underscore so it's not waiting for
00:19:10.260
a response.
00:19:12.800
And this passes the value back to
00:19:16.074
the main thread, down the channel.
00:19:18.980
Back in the main thread, you call
00:19:21.984
recv() on the rx variable, the receive
00:19:24.989
side of the channel, and you pattern
00:19:27.993
match on the result.
00:19:29.810
And if you get a success value,
00:19:32.387
you can look at the contents of
00:19:34.963
the value which was sent over,
00:19:37.172
and
00:19:37.640
process that.
00:19:39.770
Or it can error, depending if something
00:19:43.054
went wrong with the transmission.
00:19:45.500
It’s a much more explicit process than
00:19:48.316
in Scala.
00:19:49.220
We’re explicitly plumbing together the sender and
00:19:51.611
the receiver by creating the channel.
00:19:56.720
And the two approaches behave quite differently.
00:20:00.800
The approach taken in Scala and Akka
00:20:04.098
lets you couple weakly-typed processes together.
00:20:06.926
And they can communicate in a very
00:20:10.224
asynchronous and very dynamic way.
00:20:12.680
It’s very expressive, it’s very flexible,
00:20:16.096
and it's got a reasonably interesting error
00:20:20.082
handling model using
00:20:21.890
separate processes for error handling which we'll
00:20:25.117
talk about later.
00:20:26.600
And it makes it relatively easy to
00:20:29.727
upgrade the system by dynamically inserting actors
00:20:32.853
into the system as needed, by building
00:20:35.980
systems which can which can deal with
00:20:39.107
optional messages.
00:20:40.100
And the checking happens at runtime,
00:20:43.130
and so you get probabilistic guarantees of
00:20:46.665
correctness. The system can fail at runtime,
00:20:50.200
due to not understand sending messages.
00:20:53.330
Rust, on the other hand, is very
00:20:55.654
statically typed, and it provides compile time
00:20:57.979
checking that a process can respond to
00:21:00.303
all the messages it’s sent. But,
00:21:02.295
it's more explicit, it requires more plumbing
00:21:04.620
to connect the channels together.
00:21:06.380
And it needs more explicit error handling,
00:21:09.121
so there's perhaps more overhead there.
00:21:11.570
Essentially, is the usual static versus dynamic
00:21:13.822
typing debate, but playing out in types
00:21:16.073
of messages you’re exchanging.
00:21:19.850
And that's it for this part.
00:21:22.031
I spoke about actors and message passing,
00:21:24.575
and the different types and structures of
00:21:27.120
message passing systems.
00:21:28.310
In the next part, I’ll finish up
00:21:30.974
by talking about race conditions, and the
00:21:33.638
reasons why these systems are built using
00:21:36.302
immutable data, or the reason why they
00:21:38.966
track ownership to avoid races between actors.
Part 4: Race Conditions
The final part of the lecture discusses race conditions. It introduces
what is a race condition, why they're problematic, and how they can
occurs in both message passing and shared memory systems.
00:00:00.000
In this final part of the lecture
00:00:02.013
I want to talk briefly about race
00:00:04.025
conditions. I’ll talk about what is a
00:00:06.038
race condition, and how race conditions can
00:00:08.051
occur in message passing and shared memory
00:00:10.063
systems.
00:00:13.891
So, what is a race condition?
00:00:16.321
A race condition can occur when the
00:00:18.654
behaviour of a system depends on the
00:00:20.988
relative timing of different actions, different events,
00:00:23.321
that can occur,
00:00:24.421
or when a shared value is modified
00:00:27.066
without coordination between the different threads,
00:00:29.333
the different parts of the system,
00:00:31.601
which are modifying that value. And it
00:00:34.246
introduces non deterministic behaviour into the program.
00:00:36.991
It's difficult to predict the exact timing
00:00:39.858
behaviour of a program. It’s difficult to
00:00:42.725
predict what happens if multiple threads asynchronously
00:00:45.592
modify a shared value. And, as a
00:00:48.459
result, you get hard to debug problems,
00:00:51.326
and behaviour which is not predictable from
00:00:54.193
the system as a whole.
00:00:56.341
There are two types of race that
00:00:59.263
can fundamentally happen. In message passing systems,
00:01:02.184
you can get races due to the
00:01:05.106
order in which messages arrive, and in
00:01:08.028
shared memory systems you can get,
00:01:10.532
in addition, races due to modification of
00:01:13.454
values.
00:01:16.501
In message passing systems, the race condition
00:01:19.742
can occur when messages are received from
00:01:22.983
multiple senders to a particular receiver.
00:01:25.861
In these types of systems, the runtime
00:01:28.311
ensures that the receiver processes the messages
00:01:30.761
sequentially, and processes the messages in the
00:01:33.211
order that they’re received.
00:01:34.711
But, unfortunately, the order in which the
00:01:37.400
messages are received can vary.
00:01:39.421
And the order the messages are received
00:01:42.621
can vary because of system load,
00:01:45.363
because of network load, because of details
00:01:48.563
in the scheduling processes,
00:01:50.491
if a network is involved, because of
00:01:53.501
congestion control or packet loss, for example.
00:01:56.611
And, as a result, the messages,
00:01:58.751
if you have messages arriving at receiver
00:02:01.248
from multiple senders, can arrive in unpredictable
00:02:03.744
order.
00:02:04.201
You’re not always guaranteed that a message
00:02:07.060
from sender one will necessarily arrive before
00:02:09.919
a message from sender two.
00:02:12.061
And, if it matters which order the
00:02:15.141
messages arrive in,
00:02:16.561
if the system takes different actions,
00:02:18.950
depending on the order the messages arrive,
00:02:21.736
you then have the potential for unpredictable
00:02:24.523
behaviour.
00:02:25.021
Similarly, it's possible for such a system
00:02:27.595
to deadlock. It’s possible to arrange the
00:02:30.170
system such that the messages flow in
00:02:32.744
a cycle, and if the timing doesn't
00:02:35.319
work out, the actors end up waiting
00:02:37.893
for messages from each other in a
00:02:40.468
mutually dependent loop.
00:02:41.671
Again, if this is likely to be
00:02:44.597
a problem, you need to structure the
00:02:47.522
communication differently, so there are no loops
00:02:50.448
of messages, and so there's no chance
00:02:53.373
of things accidentally ending-up mutually dependent.
00:02:55.981
Essentially, in message passing systems, you're building
00:02:58.477
a network protocol. And the tools which
00:03:00.972
we have to analyse network protocols,
00:03:03.111
to detect deadlocks and detect race conditions
00:03:05.607
in network protocols, can also be applied
00:03:08.102
to the patterns of communication in actor
00:03:10.598
based systems.
00:03:15.451
In shared memory systems it's also possible
00:03:18.690
to get these types
00:03:20.641
of race conditions, due to the timing
00:03:23.369
at which communications happens between different threads.
00:03:26.096
And it's also possible to get deadlocks
00:03:28.824
because of acquiring locks in the wrong
00:03:31.551
order.
00:03:32.041
But there's also a third type of
00:03:34.373
race, which is what's known as a
00:03:36.705
data race.
00:03:37.471
Now, in shared memory systems,
00:03:40.981
when two threads communicate, we're conceptually moving
00:03:44.276
the data from one thread to another.
00:03:47.671
So, conceptually, the data goes from one
00:03:50.421
thread, and is moved to the other
00:03:53.170
thread. The sender loses access to the
00:03:55.920
data after it has been sent,
00:03:58.277
and the receiver gains access, and there's
00:04:01.027
no potential for a race.
00:04:03.091
In practice, though, in order to get
00:04:05.508
good performance, what often happens is that
00:04:07.924
a reference to the data is moved.
00:04:10.441
And for performance reasons, the underlying data
00:04:13.390
remains in place, and quite often it's
00:04:16.339
possible, the result is incorrect, but it's
00:04:19.287
possible for the sender to keep a
00:04:22.236
reference to the data after it has
00:04:25.185
been passed to the receiver.
00:04:27.391
And this allows the possibility of what's
00:04:30.096
known as a data race. Where both
00:04:32.800
the sender and the receiver have access
00:04:35.505
to the same piece of data ,and
00:04:38.210
the sender modifies it after it's been
00:04:40.915
sent.
00:04:41.401
And the problem with this, is that
00:04:44.101
it's unpredictable at what point that modification
00:04:46.800
happens, and whether it becomes visible to
00:04:49.500
the receiver before, or after, it uses
00:04:52.200
the value.
00:04:53.071
Depending on the timing of the changes,
00:04:55.677
depending on the scheduling, it's possible that
00:04:58.283
the receiver may see the modified value,
00:05:00.888
or it’s possible that it won’t,
00:05:03.122
leading to unpredictable behaviour.
00:05:04.711
And are two approaches to avoid this,
00:05:06.976
as you might expect.
00:05:08.371
One is immutable data: make sure the
00:05:10.842
data can’t change. And the other is
00:05:13.312
tracking ownership, to make sure that it
00:05:15.783
really is, make sure that the reference
00:05:18.253
really is moved to the receiver.
00:05:22.411
So, the common approach to avoiding data
00:05:25.278
races is just to make the data
00:05:28.146
immutable. Make sure that anything which is
00:05:31.013
sent between threads cannot be modified.
00:05:33.571
And languages like Erlang, which make extensive
00:05:37.046
use of message passing, ensure this by
00:05:40.522
making all variables immutable. You simply can't
00:05:43.997
change the value, you can’t change the
00:05:47.472
value of a variable in Erlang.
00:05:50.551
And that works, and it certainly avoids
00:05:54.164
the race conditions, but it forces quite
00:05:57.777
a different programming style.
00:05:59.941
Alternatively, you have languages like Scala with
00:06:03.651
the Akka library
00:06:05.341
which, again, are widely used for message
00:06:08.787
passing systems.
00:06:09.871
But the language doesn't enforce immutability.
00:06:12.526
It has tools to enable it,
00:06:15.180
but it requires programmer discipline. It requires
00:06:18.277
the programmer to track what values which
00:06:21.374
can be passed between threads, and ensure
00:06:24.471
it treats them immutably.
00:06:26.341
And this opens up the potential for
00:06:29.148
race conditions if message data is modified
00:06:31.955
after the messages are sent. And it's
00:06:34.762
a source of bugs in those types
00:06:37.569
of language.
00:06:40.651
The other way of avoiding data races,
00:06:44.246
avoiding race conditions, is by transferring ownership.
00:06:47.941
Race conditions, obviously, can't occur if the
00:06:51.399
data isn't shared.
00:06:52.981
If we make sure that the ownership
00:06:55.483
of the object is actually being transferred,
00:06:57.986
so the sender can't access it after
00:07:00.488
it has been sent. And if the
00:07:02.991
program, and the compiler, and the runtime,
00:07:05.493
can somehow enforce that, then you're guaranteed
00:07:07.996
that races can't occur, even if the
00:07:10.498
values are mutable.
00:07:11.671
And this is a natural fit for
00:07:14.597
the way Rust works. The standard library
00:07:17.524
in Rust provides an abstraction known as
00:07:20.450
a channel, which allows for communication between
00:07:23.377
threads, and it provides send() and recv()
00:07:26.303
functions.
00:07:26.821
The send() function on a channel takes
00:07:29.616
ownership of the data to be sent,
00:07:32.411
and the recv() function, called by the
00:07:35.206
receiving thread, returns ownership of that data.
00:07:38.101
And the type system of Rust,
00:07:40.236
because it tracks ownership, can actually make
00:07:42.726
this work, so that once the value
00:07:45.217
is sent into a channel, because that
00:07:47.707
function takes ownership, the sender doesn't have
00:07:50.198
access to it anymore.
00:07:51.721
Similarly, on the receiving side, once the
00:07:54.616
receiver has called the recv() call and
00:07:57.511
returned ownership, the data is not accessible
00:08:00.407
by the channel anymore.
00:08:02.161
And the usual ownership rules in Rust
00:08:04.523
ensure that the data is not accessible
00:08:06.885
once it's been sent. And you don't
00:08:09.247
have to worry about mutability, because it's
00:08:11.609
guaranteed that once it's been sent,
00:08:13.634
the
00:08:14.071
original thread, the sending thread, loses ownership.
00:08:17.073
It can't access the object once it's
00:08:20.075
been sent, it can't change it,
00:08:22.648
and so race conditions can’t happen.
00:08:25.321
And that works well in Rust,
00:08:27.917
because it has the ability to track
00:08:30.946
ownership. It doesn't work so well in
00:08:33.974
other languages, because Rust is unusual in
00:08:37.003
having ownership tracking.
00:08:39.301
And that's essentially all I want to
00:08:42.330
say about data races.
00:08:44.161
You need to make sure that the
00:08:46.508
system is structured to avoid race conditions,
00:08:48.855
avoid data races. And you can either
00:08:51.203
do that by making the messages immutable,
00:08:53.550
or by tracking ownership.
00:08:54.991
If you do either of these,
00:08:57.790
you can actually implement message passing pretty
00:09:01.055
efficiently.
00:09:01.621
In the case where the system really
00:09:04.338
is distributed, it turns into a message
00:09:07.056
being copied across the network, but in
00:09:09.773
the case of shared memory systems,
00:09:12.103
it's implemented by passing a pointer to
00:09:14.820
the data be transferred. And
00:09:16.861
either the data is immutable, so you
00:09:19.900
don't need to worry about locking access
00:09:22.939
to it, or the type system has
00:09:25.978
tracked ownership and guaranteed that ownership has
00:09:29.017
been transferred, and again you don't need
00:09:32.056
to worry about locking access to the
00:09:35.094
data at that point.
00:09:36.931
These types of systems do, though,
00:09:39.599
interact, if you have a garbage collector.
00:09:42.811
The issue here is that
00:09:46.021
the data, which has been passed between
00:09:48.830
threads, is potentially accessible from the different
00:09:51.639
threads. And, if the multiples threads in
00:09:54.448
the system
00:09:55.351
are each running a garbage collector,
00:09:57.906
you then have to coordinate the garbage
00:10:00.887
collection between the two threads, because you
00:10:03.868
have these shared values.
00:10:05.671
And what you don't want to do,
00:10:08.878
is have one thread reaching into the
00:10:12.084
region of the heap used by another
00:10:15.391
to perform garbage collection, because this involves
00:10:18.114
locking all of the values accessed by
00:10:20.837
the other thread, and potentially stopping the
00:10:23.560
other thread while the system is running.
00:10:26.283
You want each thread to be able
00:10:29.006
to collect its garbage separately.
00:10:31.051
The usual fix for this, is that
00:10:33.388
values which are shared between threads,
00:10:35.390
because they've been passed in a message,
00:10:37.727
are put into what's known as an
00:10:40.063
exchange heap.
00:10:40.831
The system allocates a separate region of
00:10:44.063
memory for potentially shared values
00:10:46.471
and
00:10:48.181
it ensures that any access to these
00:10:51.300
values is synchronised. So a lock is
00:10:54.420
acquired, and
00:10:55.411
this makes sure that the garbage collector
00:10:59.424
can safely look for pointers from that
00:11:03.438
heap.
00:11:04.111
And it only has to lock memory
00:11:06.543
access while it's accessing the exchange heap,
00:11:08.974
which hopefully has a very small number
00:11:11.406
of values in it, and so is
00:11:13.837
quick to garbage collect. The vast majority
00:11:16.269
of the data is not shared between
00:11:18.700
threads, and so can be garbage collected
00:11:21.132
in the usual way.
00:11:22.621
So this can improve performance significantly,
00:11:25.577
if you have garbage collection,
00:11:28.141
and you're passing data between multiple threads.
00:11:34.771
So, to finish up.
00:11:39.211
As we've seen, in this part,
00:11:41.960
in the previous part, message passing is
00:11:45.168
an alternative concurrency mechanism.
00:11:47.101
And it's getting increasingly popular.
00:11:49.681
It’s available in languages like Erlang,
00:11:53.178
and in Scala with the Akka toolkit,
00:11:57.257
and it works extremely well.
00:12:00.271
It's available in Rust, it's perhaps not
00:12:02.726
so fashionable there, people seem to like
00:12:05.181
the asynchronous approach which we'll talk about
00:12:07.637
in the next lecture in Rust,
00:12:09.841
but message passing is certainly possible.
00:12:12.954
And it's possible in languages like Go,
00:12:16.586
with Go routines, and with systems like
00:12:20.218
ZeroMQ for C programs, and so.
00:12:23.431
I think the reason it's popular is
00:12:25.819
because it's easy to reason about.
00:12:27.865
It's a simple programming model.
00:12:29.671
We used to building networked systems,
00:12:32.223
and it brings in the same programming
00:12:35.200
model for communication between threads. And it
00:12:38.177
makes the communication explicit, and it's clear
00:12:41.154
when messages are being passed.
00:12:43.381
And if you have ownership tracking,
00:12:45.537
or if the data is immutable,
00:12:47.693
it's also pretty safe.
00:12:49.231
You still have the potential for race
00:12:52.377
conditions, due to the ordering between messages,
00:12:55.522
but it
00:12:56.521
avoids a lot of the
00:12:59.341
synchronisation issues with multi-threaded code.
00:13:04.771
So, that's all I have for this
00:13:07.682
lecture. We spoken about concurrency, and the
00:13:10.592
different memory models. We spoke about transactions,
00:13:13.503
and we spoke about message passing systems
00:13:16.414
and race conditions.
00:13:17.761
In the next lecture, I’ll move on
00:13:20.019
to talk about asynchronous programming.
Discussion
Lecture 7 focussed on concurrency. It stared with a discussion on the
implications of modern multi-core hardware for concurrent programming,
and a discussion of the limitations of shared state concurrency using
threads and locks. Then, it discussed two alternative approaches to
concurrent programming, using transaction and using message passing.
The transactional approach structures a program as a sequence of atomic
actions, that obey the ACID properties, and that execute concurrently.
It provides a clean programming model, that avoids race conditions and
deadlocks, and allows straightforward composition of functions. But, in
order to do this, it requires control over I/O operations and memory
access. As the lecture discusses, this is a natural fit for Haskell, but
fits less cleanly with more mainstream languages.
Message passing, rather, structures the program as a set of actors that
communicate solely by exchanging messages. The lecture discussed the
structure of an actor-based system, the types of messages passing and
the interaction models, differences between statically and dynamically
typed actor-based systems, and differences between channel-based and
direct communication. It used Scala with Akka, and Rust, as examples.
Discussion will focus on the need for alternatives to shared state
concurrency with threads. On the applicability of the transactional
programming model. And on the suitability of message passing.