Skip to content

Commit a361fd5

Browse files
committed
Add about using interior mutability
1 parent 10610e4 commit a361fd5

File tree

2 files changed

+97
-1
lines changed

2 files changed

+97
-1
lines changed

src/peripherals/singletons.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ fn main() {
2323

2424
But this has a few problems. It is a mutable global variable, and in Rust, these are always unsafe to interact with. These variables are also visible across your whole program, which means the borrow checker is unable to help you track references and ownership of these variables.
2525

26-
Up until Rust 2024, the usage of static **mutable** variable has been discouraged. Since Rust 2024, static mutable variable results in an error. Of course, there are legitimate use case of having a shared mutable state, it's just that Rust want you to really think about the scope of the mutability. We'll talk about this later when we talk about internal mutability.
26+
Up until Rust 2024, the usage of static **mutable** variable has been discouraged. Since Rust 2024, static mutable variable results in an error. Of course, there are legitimate use case of having a shared mutable state, it's just that Rust want you to really think about the scope of the mutability. We'll talk about this later when we talk about interior mutability.
2727

2828
## How do we do this in Rust?
2929

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# Interior Mutability
2+
3+
What's the matter of using `static mut` variables anyway?
4+
5+
In Rust, whenever we have a variable `foo`, only one of the following may happen:
6+
7+
* the variable `foo` is moved to another place. Subsequent reference of `foo` would be a compile failure as the value has been moved.
8+
* some number of `&foo` borrows, which allow read-only access.
9+
* a single (exclusive) `&mut foo` mutable borrow, which allow read/write.
10+
11+
One consequence of a `static` variable is that it cannot be moved, as it lives _statically_ in memory, meaning it is in a fixed place.
12+
13+
A `static` variable can be borrowed as `&foo` without much issue as it is just reading.
14+
15+
The problem occurs when we try to borrow is as mutable. Consider the following:
16+
17+
```rust,ignore
18+
static mut flag: bool = false;
19+
20+
21+
fn first() {
22+
if !flag {
23+
flag = true;
24+
println!("first");
25+
}
26+
}
27+
28+
fn second() {
29+
if !flag {
30+
flag = true;
31+
println!("second");
32+
}
33+
}
34+
```
35+
36+
The question is, which one would run? It's not obviousy just looking at a code. Perhaps it depends on the order or execution, which would be guaranteed _if_ there's only one active execution at a time.
37+
38+
You may think that because you're in an embedded programming land and you only have single core, you don't have to think about race condition, but even with a single core CPU without making any thread, you may have interrupts and those interrupt requests may access the shared mutable variable `flag`. The issue here is that the compiler cannot prohibit you from taking multiple mutable reference to the shared mutable variable at compile time, especially since it does not know about the order of executions of threads or interrupts, for example.
39+
40+
Also, the use of `static mut` variables _might_ be deprecated in the future. There's a strong indication of this and having the usage `deny` by default since Rust 2024 is one of them.
41+
42+
## So what is interior mutability?
43+
44+
Interior mutability is a way to "trick" the borrow checker to mutate a borrowed reference `&foo` (notice the lack of `&mut`). This is basically us saying to the compiler "I'm going to mutate the shared reference anyway, please don't stop me.".
45+
46+
Of course, mutating something that is borrowed in other places are undefined behaviors (UB), yet there is a way of doing so, using an `UnsafeCell`. As the name implies, you need to use the `unsafe` keyword when using it.
47+
48+
The usage looks like this:
49+
50+
```rust,ignore
51+
static flag: UnsafeCell<bool> = UnsafeCell::new(false);
52+
53+
fn some_usage() {
54+
// Here we take a mutable __pointer__ out of `flag`, even though
55+
// it is a normal static variable without `mut`.
56+
57+
let my_mutable_flag_ref: *mut bool = flag.get();
58+
59+
// what we have now is a mutable __pointer__, not a reference.
60+
// Now, it is obvious that we are dealing with unsafe behavior.
61+
62+
unsafe {
63+
if *flag == false {
64+
*flag = true;
65+
println!("set the flag to true");
66+
}
67+
}
68+
}
69+
70+
```
71+
72+
Compared to `static mut`, now we make it obvious that what we are trying to do is unsafe and we promise to the compiler to be careful.
73+
74+
One small lie here is that you cannot use `UnsafeCell` in a static variable that way because it does not implement `Sync`, which means it is not thread-safe (or interrupt safe for that matter).
75+
76+
We could ignore all of the safety in Rust 2024 by using SyncUnsafeCell. If you want to implement it yourself, this is all you need to write:
77+
78+
```rust,ignore
79+
80+
#[repr(transparent)]
81+
pub struct SyncUnsafeCell<T>(UnsafeCell<T>);
82+
83+
unsafe impl<T: Sync> Sync for SyncUnsafeCell<T> {}
84+
85+
```
86+
87+
where Sync does absolutely nothing.
88+
89+
Another way is to use Rust's `SyncUnsafeCell` which is currently only available in nightly under the flag `#![feature(sync_unsafe_cell)]`.
90+
91+
92+
Of course, none of the above are safe. In order to get a proper interior mutability that is safe, we should implement `Sync` ourself and put in our synchronization primitive specific to the hardware such as locking the resource with atomic swap and guarding the code with interrupt-free section (disable interrupt, run some code, enable interrupt), also known as critical section.
93+
94+
You could check how [rust-console gba](https://github.com/rust-console/gba/blob/6a3fcc1ee6493a499af507f8394ee542500721b7/src/gba_cell.rs#L63) implement it for reference.
95+
96+
Interior mutability and static mutability is a rather deep topic. I strongly recommend reading more about static mutable references from [the rust edition guide here](https://github.com/rust-lang/edition-guide/blob/master/src/rust-2024/static-mut-references.md).

0 commit comments

Comments
 (0)