liveBook · Manning

Static mut

As explained in Learn Rust in a Month of Lunches

A static mut is a Rust static value that can be directly modified, but accessing it requires unsafe code because unsynchronized access can violate aliasing rules or cause data races.

A static mut is a Rust static value that can be changed directly throughout a program. Because unsynchronized access can cause aliasing violations or data races, reading or modifying one requires an unsafe block. section 16.4 section 16.4.2

A counter shared by threads

static mut NUMBER: u32 = 0;\n\nfn main() {\n let mut handles = vec![];\n for _ in 0..10 {\n handles.push(std::thread::spawn(|| {\n for _ in 0..10 {\n unsafe { NUMBER += 1; }\n }\n }));\n }\n for handle in handles { handle.join().unwrap(); }\n unsafe { println!("{NUMBER}"); }\n}\n\nTen threads may produce 100, but increasing the test to 1,000 threads with 1,000 increments can produce inconsistent totals such as 959,696. Threads can read the same value, increment separately, and overwrite one another’s updates. section 16.4.2

error[E0133]: use of mutable static is unsafe and requires unsafe function
or block
 --> src/main.rs:4:5
  |
4 |     NUMBER += 1;
  |     ^^^^^^^^^^^ use of mutable static
  |
  = note: mutable statics can be mutated by multiple threads: aliasing
violations or data races will cause undefined behavior

The compiler diagnostic identifies mutable-static access as unsafe and names aliasing violations and data races as the reason. section 16.4.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Demonstrates declaration, compiler rejection, unsafe access, and nondeterministic threaded results, but does not develop a safe replacement.
Examples
Uses NUMBER, a ten-thread increment test, and a thousand-thread stress test with inconsistent totals.
What you can do after
Diagnose why mutable-static access requires unsafe blocks and why unsynchronized increments can produce undefined behavior.
How it connects
Connects mutable statics to unsafe Rust, const values, Mutex, threads, aliasing violations, data races, and undefined behavior.

Also explained in

Compare how 2 books explain static mut →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.