@@ -1122,6 +1122,41 @@ static bits_n_strings: BitsNStrings<'static> = BitsNStrings {
1122
1122
};
1123
1123
~~~~
1124
1124
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
+
1125
1160
### Traits
1126
1161
1127
1162
A _ trait_ describes a set of method types.
0 commit comments