Mutex Magic: Ensuring Thread Safety in Concurrent Programming in Rust

Hello Everyone, Meet "Mutex,” the cool-headed bouncer at the thread party, making sure everyone takes turns on the coding dance floor

Raunak
Rustaceans
Published in
4 min readJan 4, 2024

--

Get ready to groove as we unravel the beat behind Mutex in this tech-tango of synchronisation. Usage of mutex can easily backfire, i.e., the performance of an application can suffer a major hit if “mutex” is used wrongly.

Let's take a look at how the performance will be impacted. So Mutex is nothing but a structure that has been wrapped around critical data, and only the current accessing thread can modify it. There are mainly two operations that define its core functionality, and those are “lock” and "unlock.”.

lock: when any incoming thread comes to edit the piece of data, that thread makes an attempt to take a lock, and if it successfully gets the lock, it has access to the data.

unlock: this operation can only be done by the thread that currently has access to the mutex. by doing this operation the current thread relases the lock that it has with itself and free’s the mutex so another threads can gain access and modify the data.

So the life cycle of mutex is like below:

  1. A thread tries to access the mutex by calling “lock” method
  2. If the requesting thread gets the "lock," it will have access to the data.
  3. If not, the thread will wait for access.
  4. Last but not least, once the work is done, the thread will release the lock, and Mutex will be free.

So in a nutshell, this is how a mutex works, but there’s more that meets the eye, When many threads access the same of information, the locking needs to handled very neatly because there could be a case where two threads access mutex at same of point time, Now they try to obtain the lock and think that both of the threads have access to it, but this will bypass the main purpose of mutex.

To do operations at that speed and accuracy, we need the CPU’s help, which brings us to the concept of “atomic operations”, These atomic operations are a set of functions that are defined within the OS (“compare-and-set” or “test-and-set”), and they help us solve the above-mentioned problem. These functions take some parameters, like

  • where the value needs to be updated.
  • what value is to be updated.
  • What values will be compared?

Using this atomic operation with the help of the CPU, we are now sure that no two threads will try to access the shared resource at the same point in time. But there’s one more important part which needs to be taken care of🤖🤖🤖

Yes, as we mentioned in the 3rd point, if mutex is already locked and another thread makes a request to mutex, the thread will wait until it gets the lock to mutex, so there’s a queue in which a thread waits until its turn comes to lock the mutex.

For a thread to wait, we again need the CPU’s help. The CPU has system calls that basically synchronise various threads and processes and give them the ability to wait.

So this basically sums up the implementation of mutex. Let's take a look at its usage in a programming language. We’ll use Rust for this purpose.

use std::sync::Mutex;

pub fn myMutex(){
let counter = Mutex::new(0); // created a mutex with value 0
let mut new_data = counter.lock().unwrap().add_assign(10);// accessing mutex's data and changing it by calling lock method
println("{:?}",new_data); // 10
} // Here, the `counter` variable goes out of scope, hence lock will be released.

This is a very basic example, where just the main thread tries to access the mutex and updates the data. Also, you can find more methods available on mutex in rust. To ensure thread safety, mutex is not the only way; there are many other ways we can ensure thread safety in Rust.

This brings us to end of the blog, A big shoutout to you guys for reading up until here. 😉

Stay curious!!!

Rustaceans 🚀

Thank you for being a part of the Rustaceans community! Before you go:

  • Show your appreciation with a clap and follow the publication
  • Discover how you can contribute your own insights to Rustaceans
  • Connect with us: X | Rust Bytes Newsletter

--

--