US
14 MIN READ TIME

RUST

How to develop multi-threaded code

Mihalis Tsoukalos explains all you need to know about Rust and concurrency so you can assemble efficient multi-threaded tools.

OUR EXPERT Mihalis Tsoukalos is a systems engineer and a technical writer. Find him online at @mactsouk.

QUICK TIP

Get the code for this tutorial from the Linux Format archive: www. linuxformat. com/archives ?issue=292. You can learn more about Rust at www. rust-lang.org.

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.rsis 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 simple.rsdoesn’t behave as expected. The messages from the threads aren’t printed on screen, mainly because the main() function (in reality the thread used for executing the main() function) doesn’t wait for the five threads to finish – we can add an additional thread::sleep() call after the for loop for the main() thread to wait, but we can’t depend on such arbitrary parameters because we still don’t know how long it’s going to take the threads to finish and whether the sleep duration of the main() thread is going to give enough time to them.

The error message in erroneous.rs and a hint about the solution produced by the Rust compiler when trying to compile it.

So, in our case, the main() function ends first, which means the entire program ends without giving the threads enough time to do their jobs. Additionally, the for loop in simple.rsignores the value of the loop parameter. But what happens if we want to print the value of the loop parameter? Read on!

Unlock this article and much more with
You can enjoy:
Enjoy this edition in full
Instant access to 600+ titles
Thousands of back issues
No contract or commitment
Try for 99c
SUBSCRIBE NOW
30 day trial, then just $9.99 / month. Cancel anytime. New subscribers only.


Learn more
Pocketmags Plus
Pocketmags Plus

This article is from...


View Issues
Linux Format
Summer 2022
VIEW IN STORE

Other Articles in this Issue


WELCOME
MEET THE TEAM
This issue we’re diving into the kernel’s graphic
New world order!
It can feel like desktop Linux users are
REGULARS AT A GLANCE
The complete history of Unix commits
Want to feel old? A project on GitHub gathers together over 50 years of Unix commits for your delectation
AMD FidelityFX Super Resolution goes open source
AMD’s performance-enhancing upscaling technology is now open source with version 2.0.
HP launches Linux laptop
HP Dev One comes with Linux Pop!_OS preinstalled.
SEE YOU IN VALHALL!
Alyssa Rosenzweig is a software engineer at Collabora.
CRITICAL THINKING
Keith Edmunds is MD of Tiger Computing Ltd,
Microsoft gives Gnome a boost
Thanks to Microsoft staff and its FOSS Fund.
Ubuntu Touch OTA-23 released
Supported devices getting the Ubuntu release for mobiles.
Thunderbird 102 now available
Big update for the open source email client.
Distro watch
What’s down the side of the free software sofa?
THANKS ADMINS!
Matt Yonkovit is the head of open source
GO RUST!
Jon Masters is a kernel hacker who’s been
Kernel Watch
Jon Masters summarises the latest happenings in the Linux kernel, so that you don’t have to.
Answers
Got a burning question about open source or the kernel? Whatever your level, email it to lxf.answers@futurenet.com
Mailserver
Is there a lowlatency kernel for the Jellyfish?
LETTER OF THE MONTH
We’re not sure this is a punishment or
Mayank Sharma
After being given an offer he couldn’t refuse,
Speek
Version: 1.6.0 Web: https://speek.network S peek
zuluCrypt
Version: 6.1.0 Web :https:// mhogomchungu.github.io/zuluCrypt/ Use zuluCrypt
Bpytop
Version: 1.0.68 Web: https://github . com/aristocratos/bpytop You
Converseen
Version: 0.9.9.5 Web: https:// converseen.fasterland.net Besides
SYSTEM PROFILER inxi
Version: 3.3.16 Web: https://github . com/smxi/inxi While
Qrencode
Version: 4.1.1 Web: https://fukuchi.org/ works/qrencode Remember that
Espanso
Version: 2.1.5-beta Web: https://espanso.org Espanso has some
nudoku
Version: 2.1.0 Web: https://github.com/jubalh/nudoku If you
Powder Toy
Version: 96.2 Web: https://powdertoy.co.uk It might not
Cerebro
Version: 0.5.0 Web: https://cerebroapp.com While Cerebro is
Flatseal
Version: 1.8.0 Web: https://github.com/ tchx84/flatseal While most
CODE, SCRIPT AUTOMATE!
Make your Linux life easier with hacks, scripts and coding secrets to automate your world.
LINUX Format
The #1 open source mag Future Publishing Limited,
REVIEWS
Backblaze B2
A simple pricing model makes it easy to migrate to, says Jonas DeMuro.
Intel Core i3-12100
A lowly quad-core serves up big performance gains, finds Paul Alcorn.
GeckoLinux Static 153
Michael Reed takes a close look at GeckoLinux, a distro with a wide variety of editions that puts a friendly face on openSUSE.
MakuluLinux Shift
Michael Reed is wowed by the visual bling of MakuluLinux, a distro that claims to be ‘game ready’ thanks to its many pre-installed components.
EasyOS 4.2
Michael Reed tries a Linux distribution that’s suitable for extremely limited hardware, and finds that it breaks with conventions in some areas.
Inscryption
We’re not trapped in here with The Management, they’re trapped in here with Jody Macgregor. And that’s just the way we like it.
ROUNDUP
Software whiteboards
If you’re starting a project you’ll need to take notes, possibly for presentation down the line. Mats Tage Axelsson helps you to organise your thoughts.
Installation options
How you choose to install will make a difference when you want to upgrade.
Whiteboard or notepad?
Do you need to take notes or capture your audience’s attention?
Day-to-day usability
Choose a program to meet your needs.
File export and import options
Combining files for pleasing visuals requires more than one file format.
Variety of modules
Tools that can visualise objects are invaluable for demonstrating concepts.
Development maturity
To evaluate these packages we need to know how far along the project is.
Making live presentations
Use these programs to create a presentation or interactive discussion.
The Verdict
Software whiteboards
HACK YOUR GRAPHICS
Join pixel-eyed Jonni Bidwell on a quest to demystify the world of graphics on Linux.
In the beginning…
Linux still talks to LCD monitors via a CRT controller interface. Find out where that came from!
Into a third dimension
We add some depth to the story and learn about the first, bona fide, GPU.
MESA TODAY
OpenGL remains the biggest API supported by Mesa
Querying your 3D stack
Intel’s numbering systems make no sense, but whatever your card there’s plenty of demos to play with…
Hack your graphics
Switch drivers, interrogate GPU memory, try and keep the magic smoke from escaping into the atmosphere…
Of GPUs and APIs…
And leave us nought but grief and pain… isn’t thankfully something Linux users have to experience these days!
Pi USER
DOING MORE WITH LESS
Les Pounder works with groups such as the
Raspberry Pi Pico W
Solid hardware, good software and Wi-Fi access see this incremental update elevate the Pico to a truly versatile dev board – just how Les Pounder likes it!
Adding distance sensors to projects
Les Pounder merges two low-cost, yet complex ultrasonic sensors to create one must-have Pi-powered gadget that anyone can use.
Build light shows with multi-coloured LEDs
Use WLED firmware and a string of LEDs to create eye-catching light shows to display around your home, with Matthew Holder.
Build a “rubber ducky” device from a Pi Pico
Discover why the classic fake keyboard hacking device is ideal for the Raspberry Pi Pico and Matthew Holder’s very particular set of skills…
IN DEPTH
LOCAL LINUX FOR LOCAL USERS
You’re not from around here, says Aaron Peters but that’s fine! As he’s here to explain how your distro of choice gets to work in any language.
TUTORIALS
Feature-rich music players for minimalists
Simplicity, elegance, usefulness and sheer fun are all qualities that describe Shashank Sharma. They’re also features he values most in applications.
Enhance your photos quickly and easily
Nick Peers tracks down an image editor that strikes the right balance of features and user-friendliness for making quick-fire edits.
Relive the classic ARM-based RISC OS
RISC OS is an operating system with a fascinating history that dates back decades. Michael Reed tries it out in its current incarnation.
GIMP batch processing
Tackling mass image processing is a walk in the park when you have Karsten Günther on your side and BIMP installed alongside GIMP.
Using WordPress with OnlyOffice
With OnlyOffice Docs connected to WordPress, authors are able to insert documents into online posts. Kseniya Fedoruk explains how it works.
Online reproducible dev environments
Stuart Burns is your guide to Gitpod, a new ‘work from anywhere’ development platform that could revolutionise test environments.
Host your own secure VPS-based WireGuard
David Rutland takes the LXF VPS server for a final spin. This month, he’s protecting his privacy and watching Mexican TV with a self-hosted VPN.
TOP OF THE FOSS!
AWOOGA, AMIGA
Jonni Bidwell’s desk has become a retro gaming station, thanks to Dimitris Panokostas and his Amiberry emulator.
CODING ACADEMY
Adding gamepad support to Tetris
Andrew Smith likes nothing better than fitting oddly shaped blocks into oddly shaped holes, and a gamepad makes that much easier…
Chat
X
Pocketmags Support