From 8885b740f6954fb0e7c9aeabae4ad4cc2402f4c4 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Wed, 17 Jul 2013 08:51:58 -0700 Subject: [PATCH] Add documentation about mutable statics to rust.md --- doc/rust.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/doc/rust.md b/doc/rust.md index 9948ec79fc6..36ceab26b7b 100644 --- a/doc/rust.md +++ b/doc/rust.md @@ -1124,6 +1124,41 @@ static bits_n_strings: BitsNStrings<'static> = BitsNStrings { }; ~~~~ +#### Mutable statics + +If a static item is declared with the ```mut``` keyword, then it is allowed to +be modified by the program. One of Rust's goals is to make concurrency bugs hard +to run into, and this is obviously a very large source of race conditions or +other bugs. For this reason, an ```unsafe``` block is required when either +reading or writing a mutable static variable. Care should be taken to ensure +that modifications to a mutable static are safe with respect to other tasks +running in the same process. + +Mutable statics are still very useful, however. They can be used with C +libraries and can also be bound from C libraries (in an ```extern``` block). + +~~~ +# fn atomic_add(_: &mut uint, _: uint) -> uint { 2 } + +static mut LEVELS: uint = 0; + +// This violates the idea of no shared state, and this doesn't internally +// protect against races, so this function is `unsafe` +unsafe fn bump_levels_unsafe1() -> uint { + let ret = LEVELS; + LEVELS += 1; + return ret; +} + +// Assuming that we have an atomic_add function which returns the old value, +// this function is "safe" but the meaning of the return value may not be what +// callers expect, so it's still marked as `unsafe` +unsafe fn bump_levels_unsafe2() -> uint { + return atomic_add(&mut LEVELS, 1); +} + +~~~ + ### Traits A _trait_ describes a set of method types.