-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Ch. 20: Fix safety handling in the
static mut
example
- Add `SAFETY` documentation on the unsafe function and comments on the unsafe invocation in the code samples. - Discuss the soundness issues in more depth and explain the idiomatic use of those `SAFETY` comments.
- Loading branch information
1 parent
2b1ddf4
commit 48d0b76
Showing
2 changed files
with
17 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,16 @@ | ||
static mut COUNTER: u32 = 0; | ||
|
||
fn add_to_count(inc: u32) { | ||
unsafe { | ||
COUNTER += inc; | ||
} | ||
/// SAFETY: Calling this from more than a single thread at a time is undefined | ||
/// behavior, so you *must* guarantee you only call it from a single thread at | ||
/// a time. | ||
unsafe fn add_to_count(inc: u32) { | ||
COUNTER += inc; | ||
} | ||
|
||
fn main() { | ||
add_to_count(3); | ||
|
||
unsafe { | ||
println!("COUNTER: {COUNTER}"); | ||
// SAFETY: This is only called from a single thread in `main`. | ||
add_to_count(3); | ||
println!("COUNTER: {}", COUNTER); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters