Skip to content

Commit

Permalink
02_ownership: add aliasing-xor-mutability example
Browse files Browse the repository at this point in the history
  • Loading branch information
wprzytula committed Oct 2, 2024
1 parent 39ff594 commit bf447e3
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
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 content/lessons/02_ownership/aliasing-xor-mutability/src/main.rs
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);
});
});
}

0 comments on commit bf447e3

Please sign in to comment.