diff --git a/content/lessons/02_ownership/aliasing-xor-mutability/Cargo.toml b/content/lessons/02_ownership/aliasing-xor-mutability/Cargo.toml new file mode 100644 index 0000000..c4044ef --- /dev/null +++ b/content/lessons/02_ownership/aliasing-xor-mutability/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "aliasing_xor_mutability" +version = "0.1.0" +edition = "2021" diff --git a/content/lessons/02_ownership/aliasing-xor-mutability/src/main.rs b/content/lessons/02_ownership/aliasing-xor-mutability/src/main.rs new file mode 100644 index 0000000..d6fed8b --- /dev/null +++ b/content/lessons/02_ownership/aliasing-xor-mutability/src/main.rs @@ -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); + }); + }); +} \ No newline at end of file