O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Locks and mutexes

When safe access to a shared resource is required, the access can be protected by the use of a mutex. Mutex is short for mutual exclusion, a widely used mechanism for ensuring that a piece of code is executed by only one thread at a time. It works by prohibiting access to a value from more than one thread at a time by locking the value.

Here's a piece of code that illustrates how this protection works at compile time:

// mutexes-1.rs use std::sync::Mutex; fn main() {     let mutexed_number = Mutex::new(5);     println!("Mutexed number plus one equals {}", *mutexed_number + 1); } 

This code fails to compile because we can get to the value protected by the mutex only by locking it first:

This version works as expected:

 // mutexes-2.rs ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required