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