Let's learn some building blocks!
Put your other projects and concerns aside. Take a breath and relax. Here are some fun resources for you to explore.
Read all the readings and perform all the exercises. Also watch the video.
-
Reading: Fearless Concurrency with Rust. This is a classic Rust blog post from Aaron Turon that clearly explains why concurrency is so easy in Rust. The title is also the origin of using the word "fearless" to describe various Rust properties.
-
Reading: What is the difference between concurrency and parallelism?. This is a 10 second read, but something to keep in mind. The two words are often used interchangably. We'll mostly use the word "concurrent" since it is more general than "parallel". Sometimes we'll use the word "parallel" to be more specific, sometimes because it sounds better…
-
Reading: Rust: A unique perspective. An explanation of the dangers of mutable aliasing and how Rust solves the problem. This one is by Matt Brubeck, from the Servo team.
-
Video: Rust Concurrency Explained. A more in-depth talk by Alex Crichton. Aaron and Alex wrote many of the concurrent data structures in the standard library. Alex has given versions of this talk for years, and it is a pretty great overview of what Rust can do.
-
Reading:
std::sync
. Once again, the standard library documentation provides not only good documentation about the library, but about the subject in general. This provides an overview of most of the concurrent types provided by the standard library. -
Exercise: Basic multithreading. This is a simple multithreading exercise from the rustlings project. It is small enough that it can be completed on play.rust-lang.org.
-
Exercise: Write a thread pool.
A thread pool runs jobs (functions) on a set of reusable threads, which can be more efficient than spawning a new thread for every job.
Create a simple thread pool with the following type signature:
impl ThreadPool { fn new(threads: u32) -> Result<Self>; fn spawn<F>(&self, job: F) where F: FnOnce() + Send + 'static; }
The
new
function should immediately spawnthreads
number of threads, and then those threads will wait for jobs to be spawned. When a thread recieves a job, it runs it to completion, then waits for the next job.The
threadpool
crate and Rayon'sThreadPool
may provide inspiration. -
Reading: Lock-free vs wait-free concurrency. It seems like everybody wants their code to be "lock-free". What's that mean?