10 Concurrent programs

 

In this chapter you will learn

  • how to declaratively design concurrent program flows
  • how to use lightweight virtual threads (fibers)
  • how to safely store and access data from different threads
  • how to process a stream of events asynchronously

We know the past but cannot control it. We control the future but cannot know it.

—Claude Shannon

Threads, threads everywhere

So far in the book we’ve been focusing on sequential programs: each program consisted of a sequence of expressions that were evaluated one by one using a single execution thread, usually connected to a single core.

We won’t be focusing on cores (or CPUs) in this chapter. We will focus on having multiple threads. Note that multiple threads can still run on a single core. The operating system switches between different threads to make sure everyone gets a chance to progress.

Declarative concurrency

Sequential vs. concurrent

Coffee break: Sequential thinking

Coffee break explained: Sequential thinking

The need for batching

Quick exercise

Batching implementation

Batching trade-offs

The concurrent world

The concurrent state

Monitors and locks