Rust's ownership and borrowing model simplifies immutable data access and transfer considerably—but what about shared states? There are many applications that require mutable access to a shared resource from multiple threads. Let's see how this is done!
Sharing mutable states
How to do it...
In this recipe, we will create a very simple simulation:
- Run cargo new black-white to create a new application project and open the directory in Visual Studio Code.
- Open src/main.rs to add some code. First, we are going to need some imports and an enum to make our simulation interesting:
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
///
/// A simple enum with only two variations: black and white
...