Samwel Charles

A Practical Introduction to Concurrency in rust

A woman Juggling

Concurrency in Rust is like juggling multiple balls at once, where each ball represents a task running independently. Rust provides a powerful set of tools for managing concurrent tasks, as well as a type-safe ownership and borrowing system to prevent data races and other concurrency issues. With Rust, you can easily build high-performance, parallel programs that take full advantage of modern multicore processors. So grab your juggling balls and get ready to build some blazing-fast concurrent programs in Rust!

This article is intended as a gentle introduction to the world of concurrent programming in Rust, and I encourage readers to continue exploring the topic beyond what I'll cover here.

Let's get jugglin'

To install two Rust crates I've used in this example Reqwest and Tokio using the Cargo package manager, you can use the following command:

The Plot

Let's consider a simple example of an image downloader in Rust that does not use concurrency. Imagine that you want to download a large number of images from the internet and save them to disk.

That would look something like this 👇🏽

Here we have are using tokio to support

download_image() function implementation

With the code that doesn't use concurrency, downloading only four(4) images can feel like watching paint dry. On my computer the task consistently takes more that 40 seconds to complete!. That's why we need to spice things up and add some concurrency to make it go faster than a cat chasing a laser pointer.

:: Published Feb 14, 2023 ::