Add global mutable state example

issue #100
This commit is contained in:
James Kominick 2017-05-19 01:13:02 -04:00
parent e01ebc6171
commit 4f61dcca7b
2 changed files with 62 additions and 0 deletions

View file

@ -10,6 +10,7 @@
| [Generate random values of a custom type][ex-rand-custom] | [![rand-badge]][rand] | [![cat-science-badge]][cat-science] |
| [Run an External Command and Process Stdout][ex-parse-subprocess-output] | [![regex-badge]][regex] | [![cat-os-badge]][cat-os] [![cat-text-processing-badge]][cat-text-processing] |
| [Declare lazily evaluated constant][ex-lazy-constant] | [![lazy_static-badge]][lazy_static] | [![cat-caching-badge]][cat-caching] [![cat-rust-patterns-badge]][cat-rust-patterns] |
| [Maintain global mutable state][ex-global-mut-state] | [![lazy_static-badge]][lazy_static] | [![cat-rust-patterns-badge]][cat-rust-patterns] |
@ -306,6 +307,62 @@ fn main() {
}
```
[ex-global-mut-state]: #ex-global-mut-state
<a name="ex-global-mut-state"></a>
## Maintain global mutable state
[![lazy_static-badge]][lazy_static] [![cat-rust-patterns-badge]][cat-rust-patterns]
Declares some global state using [lazy_static]. Since [lazy_static]
creates a globally available `static ref` we also need to wrap our state
in a [`Mutex`] to allow mutation (also see [`RwLock`]). The [`Mutex`] ensures
the state cannot be simultaneously accessed by multiple threads, preventing
race conditions. A [`MutexGuard`] must be acquired to read or mutate the
value stored in a [`Mutex`].
```rust
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate lazy_static;
use std::sync::Mutex;
error_chain!{ }
lazy_static! {
static ref FRUIT: Mutex<Vec<String>> = Mutex::new(Vec::new());
}
fn insert(fruit: &str) -> Result<()> {
// acquire exclusive access
let mut db = FRUIT.lock()
.map_err(|_| "Failed to acquire MutexGuard")?;
db.push(fruit.to_string());
Ok(())
// release exclusive access
}
fn run() -> Result<()> {
insert("apple")?;
insert("orange")?;
insert("peach")?;
{
// acquire access
let db = FRUIT.lock()
.map_err(|_| "Failed to acquire MutexGuard")?;
for (i, item) in db.iter().enumerate() {
println!("{}: {}", i, item);
}
// release access
}
insert("grape")?;
Ok(())
}
quick_main!(run);
```
<!-- Categories -->
@ -355,3 +412,6 @@ fn main() {
[`Output`]: https://doc.rust-lang.org/std/process/struct.Output.html
[`Command`]: https://doc.rust-lang.org/std/process/struct.Command.html
[`HashMap`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html
[`Mutex`]: https://doc.rust-lang.org/std/sync/struct.Mutex.html
[`RwLock`]: https://doc.rust-lang.org/std/sync/struct.RwLock.html
[`MutexGuard`]: https://doc.rust-lang.org/std/sync/struct.MutexGuard.html

View file

@ -28,6 +28,7 @@ community. It needs and welcomes help. For details see
| [Generate random values of a custom type][ex-rand-custom] | [![rand-badge]][rand] | [![cat-science-badge]][cat-science] |
| [Run an External Command and Process Stdout][ex-parse-subprocess-output] | [![regex-badge]][regex] | [![cat-os-badge]][cat-os] [![cat-text-processing-badge]][cat-text-processing] |
| [Declare lazily evaluated constant][ex-lazy-constant] | [![lazy_static-badge]][lazy_static] | [![cat-caching-badge]][cat-caching] [![cat-rust-patterns-badge]][cat-rust-patterns] |
| [Maintain global mutable state][ex-global-mut-state] | [![lazy_static-badge]][lazy_static] | [![cat-rust-patterns-badge]][cat-rust-patterns] |
## [Encoding](encoding.html)
@ -153,6 +154,7 @@ Keep lines sorted.
[ex-byteorder-le]: basics.html#ex-byteorder-le
[ex-clap-basic]: app.html#ex-clap-basic
[ex-global-mut-state]: basics.html#ex-global-mut-state
[ex-json-value]: encoding.html#ex-json-value
[ex-lazy-constant]: basics.html#ex-lazy-constant
[ex-log-custom-logger]: app.html#ex-log-custom-logger