10 Processes, threads, and containers

 

This chapter covers

  • Concurrent programming in Rust
  • How to distinguish processes, threads, and containers
  • Channels and message passing
  • Task queues

So far this book has almost completely avoided two fundamental terms of systems programming: threads and processes. Instead, the book has used the single term: program. This chapter expands our vocabulary.

Processes, threads, and containers are abstractions created to enable multiple tasks to be carried out at the same time. This enables concurrency. Its peer term, parallelism, means to make use of multiple physical CPU cores at the same time.

Counterintuitively, it is possible to have a concurrent system on a single CPU core. Because accessing data from memory and I/O take a long time, threads requesting data can be set to a blocked state. Blocked threads are rescheduled when their data is available.

Concurrency, or doing multiple things at the same time, is difficult to introduce into a computer program. Employing concurrency effectively involves both new concepts and new syntax.

10.1 Anonymous functions

10.2 Spawning threads

10.2.1 Introduction to closures

10.2.2 Spawning a thread

10.2.3 Effect of spawning a few threads

10.2.4 Effect of spawning many threads

10.2.5 Reproducing the results

10.2.6 Shared variables

10.3 Differences between closures and functions

10.4 Procedurally generated avatars from a multithreaded parser and code generator

10.4.1 How to run render-hex and its intended output

10.4.2 Single-threaded render-hex overview

10.4.3 Spawning a thread per logical task

10.4.4 Using a thread pool and task queue