Linux Format

How to develop multi-threaded code

This month’s instalment of our ongoing Rust series will cover concurrent programming. The difficulty with concurrency can be summed up as “Shared Mutable State is the root of all problems”. However, Rust takes a different approach towards concurrency. Instead of dealing with the mutable part, Rust deals with the shared part. Put simply, the Rust compiler will let you know about any errors in the “shared” part; therefore, if your Rust code compiles you have no such errors. As a result, it’s okay to have shared memory among threads in Rust.

So, it’s in concurrent programming that you might appreciate all the Rust rules regarding borrowing, ownership and mutability. To get us going we’ll present a simple concurrent Rust program that’s far from perfect.

Basic concurrency

Rust starts a new thread using the thread::spawn() function that’s part of the std::thread module. The core code of simple.rs is the following:

Two things are happening here. First, there’s a for loop used for calling thread::spawn() five times and therefore creating five threads. Second, there’s a call to thread::sleep() for delaying the termination of the thread. Threads usually don’t just print messages, but perform actual work that takes time. Let’s now run simple.rs, which generates the following output:

Start.

End.

First, bear in mind that there are two println!() statements before and after the for loop, which is the reason for the two lines of output. But where are the messages from the five threads? It looks like doesn’t behave as expected. The messages from

You’re reading a preview, subscribe to read more.

More from Linux Format

Linux Format2 min read
OBS Studio
Version: 30.0.2 Web: https://obsproject.com There are lots of good options for recording screencasts, but if you want to live-stream T your desktop, one of the best options is OBS Studio. The app works with all the major online streaming providers, s
Linux Format1 min read
Wine For Wayland
2023 was a great year for the Wayland driver for Wine. The goal was to move forward from the experimental phase and make the driver a proper upstream component. A year later, after several merge requests, many people are now already able to use the l
Linux Format2 min read
Back Issues Missed One?
ISSUE 313 April 2024 Product code: LXFDB0313 In the magazine Discover how to use the ultimate hacker’s toolkit, staying out of trouble while doing so. And join us as we take the Puppy Linux developer’s new distro for a run and explore its container

Related Books & Audiobooks