CA
  
You are currently viewing the Canada version of the site.
Would you like to switch to your local site?
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.

QUICK TIP

QUICK TIP

MUTEXES EXPLAINED

QUICK TIP

THE FORK-JOIN PARALLELISM

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

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.

You can learn more about the std::sync::mpsc module at https://doc. rust-lang. org/std/ sync/mpsc/ and about std::thread at https://doc. rust-lang.org/ std/thread/ fn.spawn. html. You can find more information about the Rayon library at https:// github.com/ rayon-rs/rayon. Finally, the Rust documentation site is at www. rust-lang.org/ learn.

A mutex is a mutually exclusive flag that enables a single thread to do something critical, in most cases changing the value of a shared variable, while the other threads are waiting for the same mutex to become available in order to get it and do their jobs on the shared variable. Therefore, a mutex allows only a single thread to have access to a piece of data at a given time. If multiple threads want to access the same data, they’ll have to wait until they get the relevant mutex. In other words, any thread that wants to access the shared data needs to acquire the lock to that mutex.

Concurrency is a way of structuring your components so that they can be executed independently when possible. In contrast, parallelism is the simultaneous execution of multiple entities. Put simply, concurrency is better than parallelism.

The thread::spawn() function that’s used for creating new threads returns a JoinHandle structure that’s “an owned permission to join on a thread”. In other words, JoinHandle provides a way to join the child thread. Usually, you’re going to use the provided JoinHandle to call the std::thread::join() method to make the main() function wait for the thread to finish. This is called fork-join parallelism because std::thread::spawn() creates a new thread whereas std::thread::join() deals with waiting for a thread to finish. The fork-join parallelism has many advantages because of its simplicity, which is its most important advantage.

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.

Once the thread is done working with the shared variable or variables, it should unlock the mutex and make it available to other threads. However, Rust does the unlocking automatically so there’s no need to call an unlock function. The disadvantage of mutexes is that you need to write extra code to use them and that if you forget to unlock a mutex, your program will most likely going to misbehave or crash – again, this is not a problem with Rust.

Another method of carrying out parallel programming is Async/ Await (Asynchronous Programming). Learn more at https://rustlang.github.io/async-book/03_async_await/01_chapter.htmland at https://moodle.cs.pdx.edu/mod/page/view.php?id=491.

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.

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 $1.39
SUBSCRIBE NOW
30 day trial, then just $13.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…
ADVERTISEMENT
braintumourcharity
thebraintumourcharity.org
magazinesdirect
www.magazinesdirect.com/lin/A68F
magzinesdirect
www.magzinesdirect.com
magazinesdirect
magazinesdirect.com
EFF
EFF.ORG
loverpaper
wwwl.loverpaper.org
BACK ISSUES MISSED ONE?
www.magazinesdirect.com
LINUX FORMAT
www.magazinesdirect.com/linux-format
techradar
techradar.com
code club
www.codeclub.org.uk
Chat
X
Pocketmags Support