-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
02_ownership: add aliasing-xor-mutability example
- Loading branch information
Showing
2 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
4 changes: 4 additions & 0 deletions
4
content/lessons/02_ownership/aliasing-xor-mutability/Cargo.toml
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 |
---|---|---|
@@ -0,0 +1,4 @@ | ||
[package] | ||
name = "aliasing_xor_mutability" | ||
version = "0.1.0" | ||
edition = "2021" |
39 changes: 39 additions & 0 deletions
39
content/lessons/02_ownership/aliasing-xor-mutability/src/main.rs
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 |
---|---|---|
@@ -0,0 +1,39 @@ | ||
fn next_int() -> i32 { | ||
42 | ||
} | ||
|
||
struct Data(i32); | ||
impl Data { | ||
fn new() -> Self { | ||
Self(0) | ||
} | ||
|
||
fn read(&self) -> i32 { self.0 } | ||
|
||
fn write(&mut self, n: i32) { self.0 = n } | ||
} | ||
|
||
fn thread1(shared_data: &mut Data) { | ||
loop { | ||
shared_data.write(next_int()); | ||
} | ||
} | ||
|
||
fn thread2(shared_data: &Data) { | ||
loop { | ||
println!("{}", shared_data.read()); | ||
} | ||
} | ||
|
||
fn main() { | ||
let mut shared_data = Data::new(); | ||
|
||
std::thread::scope(|s| { | ||
let t1 = s.spawn(|| { | ||
thread1(&mut shared_data); | ||
}); | ||
let t2 = s.spawn(|| { | ||
thread2(&shared_data); | ||
}); | ||
}); | ||
} |