Skip to content

Commit 1424afc

Browse files
author
Paul Kernfeld
committed
add immutable statics w/ parking_lot example
1 parent e8e6afe commit 1424afc

File tree

3 files changed

+89
-0
lines changed

3 files changed

+89
-0
lines changed

Cargo.lock

Lines changed: 61 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,5 @@ arc-swap = "0.4"
1919
lazy_static = "1.4"
2020
once_cell = "1.4"
2121
skeptic = "0.13"
22+
parking_lot = "0.10"
2223
phf = { version = "0.8", features = ["macros"] }

README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,33 @@ fn main() {
174174
}
175175
```
176176

177+
## Immutable static items
178+
179+
If you want flexible mutable global data, one way to accomplish it is to put a synchronization primitive into an [immutable static item](https://doc.rust-lang.org/reference/items/static-items.html). There are two broad ways to do this. One is by lazily initializing the synchronization primitive at run time using something like `lazy_static` and `once_cell`. The other way to do it is to use a synchronization primitive that can be initialized statically, such as those provided by the [`parking_lot` crate](https://docs.rs/parking_lot).
180+
181+
Advantages:
182+
183+
- `'static` lifetime
184+
- Choose your own synchronization primitive
185+
- Choose between compile time and run time initialization
186+
- Enables interior mutability
187+
188+
Disadvantages:
189+
190+
- More choices to make
191+
- `Drop` doesn't run on static items
192+
193+
The example below isn't parallel, but the `parking_lot` mutex can be used in parallel.
194+
195+
```rust
196+
static MY_DATA: parking_lot::Mutex<&str> = parking_lot::const_mutex("hello");
197+
198+
pub fn main() {
199+
*MY_DATA.lock() = "world";
200+
assert_eq!(*MY_DATA.lock(), "world");
201+
}
202+
```
203+
177204
## The `phf` crate
178205

179206
The [phf](https://github.com/sfackler/rust-phf) crate lets you generate maps at compile time.

0 commit comments

Comments
 (0)