Skip to content

Commit 78f8b40

Browse files
committed
auto merge of #7846 : alexcrichton/rust/static-mut-dox, r=pnkfelix
It's probably a good idea to at least *mention* them somewhere.
2 parents 874eb19 + 8885b74 commit 78f8b40

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

doc/rust.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1122,6 +1122,41 @@ static bits_n_strings: BitsNStrings<'static> = BitsNStrings {
11221122
};
11231123
~~~~
11241124

1125+
#### Mutable statics
1126+
1127+
If a static item is declared with the ```mut``` keyword, then it is allowed to
1128+
be modified by the program. One of Rust's goals is to make concurrency bugs hard
1129+
to run into, and this is obviously a very large source of race conditions or
1130+
other bugs. For this reason, an ```unsafe``` block is required when either
1131+
reading or writing a mutable static variable. Care should be taken to ensure
1132+
that modifications to a mutable static are safe with respect to other tasks
1133+
running in the same process.
1134+
1135+
Mutable statics are still very useful, however. They can be used with C
1136+
libraries and can also be bound from C libraries (in an ```extern``` block).
1137+
1138+
~~~
1139+
# fn atomic_add(_: &mut uint, _: uint) -> uint { 2 }
1140+
1141+
static mut LEVELS: uint = 0;
1142+
1143+
// This violates the idea of no shared state, and this doesn't internally
1144+
// protect against races, so this function is `unsafe`
1145+
unsafe fn bump_levels_unsafe1() -> uint {
1146+
let ret = LEVELS;
1147+
LEVELS += 1;
1148+
return ret;
1149+
}
1150+
1151+
// Assuming that we have an atomic_add function which returns the old value,
1152+
// this function is "safe" but the meaning of the return value may not be what
1153+
// callers expect, so it's still marked as `unsafe`
1154+
unsafe fn bump_levels_unsafe2() -> uint {
1155+
return atomic_add(&mut LEVELS, 1);
1156+
}
1157+
1158+
~~~
1159+
11251160
### Traits
11261161

11271162
A _trait_ describes a set of method types.

0 commit comments

Comments
 (0)